diff --git a/inline_snapshot/__init__.py b/inline_snapshot/__init__.py index 558a4ca..992b122 100644 --- a/inline_snapshot/__init__.py +++ b/inline_snapshot/__init__.py @@ -1,8 +1,9 @@ +from ._code_repr import HasRepr from ._code_repr import register_repr from ._external import external from ._external import outsource from ._inline_snapshot import snapshot -__all__ = ["snapshot", "external", "outsource", "register_repr"] +__all__ = ["snapshot", "external", "outsource", "register_repr", "HasRepr"] __version__ = "0.9.0" diff --git a/inline_snapshot/_code_repr.py b/inline_snapshot/_code_repr.py index ed4b5a3..ebd7bcb 100644 --- a/inline_snapshot/_code_repr.py +++ b/inline_snapshot/_code_repr.py @@ -17,13 +17,31 @@ def __init__(self, str_repr: str) -> None: def __repr__(self): return f"HasRepr({self._str_repr!r})" + def __eq__(self, other): + return code_repr(other) == self._str_repr + @singledispatch def code_repr_dispatch(v): return real_repr(v) -register_repr = code_repr_dispatch.register +def register_repr(f): + """Register a funtion which should be used to get the code representation + of a object. + + ```python + @register_repr + def _(obj: MyCustomClass): + return f"MyCustomClass({repr(obj.attr)})" + ``` + it is important to use `repr()` inside the implementation, because it is mocked to return the code represenation + + you dont have to provide a custom implementation if: + * __repr__() of your class returns a valid code representation, + * and __repr__() uses `repr()` to get the representaion of the child objects + """ + code_repr_dispatch.register(f) def code_repr(obj):