avoiding recursion in repr?

David C. Fox davidcfox at post.harvard.edu
Wed Nov 19 18:57:13 EST 2003


The __repr__ methods of the built-in list and dict objects properly 
avoid an infinite loop when you take the representation of a list or 
dictionary which contains itself (or more complicated nestings: list l1 
contains list l2 which contains l1, etc.).

Looking at the CPython source code, it seems that the Py_ReprEnter and 
Py_ReprLeave functions are used to implement this protection.

Is there any equivalent function for defining new container classes 
written in Python, or do potentially recursive containers have to be 
implemented in C?

(I could of course try to translate these functions into Python, but I'm 
not sure that would catch mixed nestings of my class and list/dict).

David





More information about the Python-list mailing list