IO.inspect() is the best thing since sliced bread

Seriously, having the option of non-intrusively adding IO.inspect() to any pipe, anywhere in the pipe is such a boon to development. I can keep it on its own line and comment out at-will.

7 Likes

Now try dbg! It’s IO.inspect with additional superpowers! Do a test by sticking it at the very end of a multi-call pipe :slight_smile:

15 Likes

Oh, this is just fantastic.
Is there perhaps a list of other great functions/macros one should know? Maybe geared towards beginners (like me)…

2 Likes

I recommend reading through all the Pages here Introduction — Elixir v1.17.3. It doesn’t take long and it’s easy to read.

4 Likes

:timer.tc returns (usually in microseconds) you how much time it took for code to run.

iex> {micros, return} = :timer.tc(fn -> :timer.sleep(700); :hello_there end)
{700762, :hello_there}

or this for extra visibility:

:timer.tc(fn -> :timer.sleep(700); :hello_there end) |> dbg()
8 Likes

Hi, There is also Kernel.inspect. IO.inspect writes to console, while Kernel.inspect returns Elixir term as string. Which is usually used to send that string to Logger.

1 Like

require IEx; IEx.pry

2 Likes

You might also like this library then, which enables doing the same but using Logger instead of IO: Untangle - logging and inspecting with code location information

2 Likes

Wow, dbg() prints every part of the pipe!

And when 1.18 is released, if you wrap it around a with, it will print every clause (and the final return) of that too!

5 Likes

This may be obvious to many, but I know people who get fixated on pipelines and never consider this: inspect is just an identity function with a side-effect (as is dbg but of course it’s a little more) meaning you can stick it anywhere, so if someone writes code like this:

foo
|> do_something(get_stuff())
|> do_something_else()

And you just wanna see get_stuff(), you can do a quick:

 foo
|> do_something(dbg get_stuff())
|> do_something_else()

Oh this is cool!

Don’t get me wrong, this is super useful sometimes but more often than not I find I don’t care about every piece and then it makes scrollback annoying, so IO.inspect is still nice for avoiding this when you want to. To me the best thing about dbg is that it automatically gives you a highlighted label!

2 Likes

In my opinion it’s amazing that you can put dbg somewhere, run iex --dbg pry -S mix phx.server and you get debug prints and an interactive debugging session.

8 Likes

:exploding_head:

I did not know that.

1 Like