Skip to content

@customize_repr

repr() can be used to convert a python object into a source code representation of the object, but this does not work for every type. Here are some examples:

>>> repr(int)
"<class 'int'>"

>>> from enum import Enum
>>> E = Enum("E", ["a", "b"])
>>> repr(E.a)
'<E.a: 1>'

customize_repr can be used to overwrite the default repr() behaviour.

The implementation for Enum looks like this:

@customize_repr
def _(value: Enum):
    return f"{type(value).__qualname__}.{value.name}"

This implementation is then used by inline-snapshot if repr() is called during the code generation, but not in normal code.

from enum import Enum


def test_enum():
    E = Enum("E", ["a", "b"])

    # normal repr
    assert repr(E.a) == "<E.a: 1>"

    # the special implementation to convert the Enum into a code
    assert E.a == snapshot(E.a)

builtin datatypes

inline-snapshot comes with a special implementation for the following types:

  • builtins.dict
  • builtins.frozenset
  • builtins.list
  • builtins.set
  • builtins.tuple
  • builtins.type
  • collections.defaultdict
  • dataclass
  • enum.Enum
  • enum.Flag
  • namedtuple

Container types like dict or dataclass need a special implementation because it is necessary that the implementation uses repr() for the child elements.

@customize_repr
def _(value: list):
    return "[" + ", ".join(map(repr, value)) + "]"

Note

using f"{obj!r}" or PyObject_Repr() will not work, because inline-snapshot replaces builtins.repr during the code generation.

customize

You can also use repr() inside __repr__(), if you want to make your own type compatible with inline-snapshot.

from enum import Enum


class Pair:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        # this would not work
        # return f"Pair({self.a!r}, {self.b!r})"

        # you have to use repr()
        return f"Pair({repr(self.a)}, {repr(self.b)})"

    def __eq__(self, other):
        if not isinstance(other, Pair):
            return NotImplemented
        return self.a == other.a and self.b == other.b


def test_enum():
    E = Enum("E", ["a", "b"])

    # the special repr implementation is used recursive here
    # to convert every Enum to the correct representation
    assert Pair(E.a, [E.b]) == snapshot(Pair(E.a, [E.b]))

you can also customize the representation of datatypes in other libraries:

from inline_snapshot import customize_repr
from other_lib import SomeType


@customize_repr
def _(value: SomeType):
    return f"SomeType(x={repr(value.x)})"