I’ve written a container type in Python and I’m trying to write a robust __repr__ method that correctly handles the case where the container contains itself.
For example, here’s what the built-in list does:
>>> x = []
>>> x.append(x)
>>> repr(x)
'[[...]]'
Container types written in C for CPython can achieve this functionality by using Py_ReprEnter and Py_ReprLeave. Is there equivalent functionality in pure-Python, or do I need to create my own?
You can create your own, but it’s a bit of a pain if you want to do it properly: you shouldn’t store a ‘being repr’d’ marker flag on the object itself because that’s not thread-safe. Instead you can store a thread-local set of your instances that are being repr’d.
A much cheaper solution is to depend on a built-in
reprthat takes care of recursion, eg.:As long as one object in a recursion loop causes
Py_ReprEnterto happen,reprcan’t form a complete loop.With the threading module: