hi, I’m the author of inline-snapshot which uses repr() to create the source representation from the value you want to snapshot.
But I have a problem with the way how repr() works.
>>> from enum import Enum
>>> E=Enum("E",["a","b"])
>>> repr(E.a)
'<E.a: 1>'
>>> repr([E.a])
'[<E.a: 1>]'
>>> repr(int)
"<class 'int'>"
There are some types which do not return a valid python representation, but could.
I know that it is not possible to change cpython just for my use cases, but I search for a way to customize it.
My current solution looks like this:
from functools import singledispatch
from unittest import mock
real_repr=repr
@singledispatch
def code_repr_dispatch(v):
return real_repr(v)
def code_repr(obj):
with mock.patch("builtins.repr", code_repr):
return code_repr_dispatch(obj)
@code_repr_dispatch.register
def _(v: Enum):
return f"{type(v).__qualname__}.{v.name}"
The problem is that I have to re-implement all possible container types to make it work recursively like
@code_repr_dispatch.register
def _(v: list):
# repr calls actually code_repr
return "[" + ", ".join(map(repr, v)) + "]"
This is because code_repr works recursive if it is called with repr()
but not if it is called with f"{value!r}" or
PyObject_Repr` in C.
My question now is: Does anyone know a way to make this work for the other two cases?
One of my Ideas is to change python and add a second optional argument to repr(obj, handler)
. The handler
would be called called before obj.__repr__
and can be used to overwrite the default behavior for a object. The implementation would be similar to my code_repr
approach but on PyObject_Repr
level. It would require a global thread-local variable to store the handler and to make recursive repr(obj) calls work. I don’t know if this idea would work out or lead to other issues.
A solution would not only be useful for inline-snapshot but also for reprlib which has the same problems with recursive calls to custom types.
My hope is to find a way to customize only the types which need customization and not all the container types. Maybe someone has an idea.