summaryrefslogtreecommitdiffstats
path: root/Lib/reprlib.py
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2010-09-13 21:36:00 (GMT)
committerRaymond Hettinger <python@rcn.com>2010-09-13 21:36:00 (GMT)
commit98a5f3f83883a6c924cfa1360647dcbf3152ea10 (patch)
treeb4cebb01dd9237c72656b942aa34406dc6fed5a0 /Lib/reprlib.py
parent9f0cbf1c727f7de884c392176ab4f19a49924c9b (diff)
downloadcpython-98a5f3f83883a6c924cfa1360647dcbf3152ea10.zip
cpython-98a5f3f83883a6c924cfa1360647dcbf3152ea10.tar.gz
cpython-98a5f3f83883a6c924cfa1360647dcbf3152ea10.tar.bz2
Issue 9840: Add reprlib.recursive_repr(), a decorator for handling recursive calls to __repr__ methods.
Diffstat (limited to 'Lib/reprlib.py')
-rw-r--r--Lib/reprlib.py31
1 files changed, 30 insertions, 1 deletions
diff --git a/Lib/reprlib.py b/Lib/reprlib.py
index 9893c71..c44c75c 100644
--- a/Lib/reprlib.py
+++ b/Lib/reprlib.py
@@ -1,9 +1,38 @@
"""Redo the builtin repr() (representation) but with limits on most sizes."""
-__all__ = ["Repr","repr"]
+__all__ = ["Repr", "repr", "recursive_repr"]
import builtins
from itertools import islice
+try:
+ from _thread import get_ident
+except AttributeError:
+ from _dummy_thread import get_ident
+
+def recursive_repr(fillvalue='...'):
+ 'Decorator to make a repr function return fillvalue for a recursive call'
+
+ def decorating_function(user_function):
+ repr_running = set()
+
+ def wrapper(self):
+ key = id(self), get_ident()
+ if key in repr_running:
+ return fillvalue
+ repr_running.add(key)
+ try:
+ result = user_function(self)
+ finally:
+ repr_running.discard(key)
+ return result
+
+ # Can't use functools.wraps() here because of bootstrap issues
+ wrapper.__module__ = getattr(user_function, '__module__')
+ wrapper.__doc__ = getattr(user_function, '__doc__')
+ wrapper.__name__ = getattr(user_function, '__name__')
+ return wrapper
+
+ return decorating_function
class Repr: