liveBook · Manning

IO.inspect/1

As explained in Elixir in Action, Third Edition

IO.inspect is an Elixir standard-library function that prints an inspected representation of a value and returns that value unchanged.

IO.inspect/1 prints an inspected representation of a value and returns that same value unchanged. This makes it safe to insert into a pipe chain while tracing how data changes. section 4.1.5 section 13.3.1

Inspecting a pipeline

Fraction.new(1, 4) |> IO.inspect() |> Fraction.add(Fraction.new(1, 4)) |> IO.inspect() |> Fraction.add(Fraction.new(1, 2)) |> IO.inspect() |> Fraction.value() prints each intermediate fraction without changing the final computation. section 4.1.5

Use IO.inspect/1 to:

  • Trace values as they move toward a failing location. section 13.3.1
  • Temporarily gather development-time information, then remove the calls after fixing the issue. section 13.3.1
iex(2)> Fraction.new(1, 4) |>
          IO.inspect() |>
          Fraction.add(Fraction.new(1, 4)) |>
          IO.inspect() |>
          Fraction.add(Fraction.new(1, 2)) |>
          IO.inspect() |>
          Fraction.value()
 
%Fraction{a: 1, b: 4}     #1
%Fraction{a: 8, b: 16}    #1
%Fraction{a: 32, b: 32}   #1

A runnable fraction pipeline shows inspection between successive transformations. section 4.1.5

How Elixir in Action, Third Edition covers it

How deep it goes
Defines printing and unchanged return semantics, but defers richer diagnostics to dbg.
Examples
Uses a piped fraction calculation to display intermediate Fraction structures.
What it assumes
Assumes familiarity with Elixir expressions, functions, structures, and the pipe operator.
What you can do after
Diagnose data-flow errors by inserting inspection into expression chains and removing it after debugging.
How it connects
Connects to the pipe operator, debugging, dbg, logging, and stack traces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.