Does Elixir anything like the method `__repr__` in Python?


#1

Does Elixir a method similar to ones Python has: __repr__ and __str__?


#2

There are String.Chars and Inspect protocols respectively


edit

Inspect comes semantically closer to __repr__ but it’s not quite the same. In elixir we display a representation suitable to debug, while in python usually displays a function/constructor call that is able to create a similar object.

String.chars is more like __str__ and should return something meaningful for humans. For a clock it could return “00:05”.

edit 2
Since I’m back to my laptop now, I’ve spraid in some links.


#3

Basically, while __repr__ should in fact always return a string representation that can be parsed back to an object when entered like that in the Python REPL, for Elixir’s Inspect this is not the case.

It is usually the case, but certain kinds of structures cannot survive the two-step structure->string->structure conversion, like functions (or any data structure containing a function in one of its fields), PIDs, Ports, etc.
Also, certain kinds of structures would be near-impossible to inspect when given a parseable representation. (Some examples: Decimal, Tensor). For these, a debugging-representation that follows the #StructureName<put_anything_here>-format is used.

String.Chars is used also when doing string interpolation using e.g: "#{foo}".