Python's print
statement normally seems to print the repr()
of its input. Tuples don't appear to be an exception:
>>> print (1, 2, 3)
(1, 2, 3)
>>> print repr((1, 2, 3))
(1, 2, 3)
But then I stumbled across some strange behavior while messing around with CPython's internals. In short: if you trick Python 2 into creating a self-referencing tuple, printing it directly behaves completely differently from printing its repr()
/ str()
/ unicode()
representations.
>>> print outer # refer to the link above
((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
... many lines later ...
((((((((((Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError: stack overflow
>>> print repr(outer)
((...),)
>>> print str(outer)
((...),)
>>> print unicode(outer)
((...),)
So what exactly is print
doing? In an attempt to answer this question myself, I referred to the language reference:
6.6. The
And the rules for string conversions are:
5.2.9. String conversions
A string conversion is an expression list enclosed in reverse (a.k.a. backward) quotes:
string_conversion ::= "`" expression_list "`"
But enclosing outer
in back quotes has the same result as calling repr()
and friends. No dice. So what the heck is print
actually doing behind the scenes?
(Interestingly, the behavior is "fixed" in Python 3: printing a self-referencing tuple gives the ellipsis-truncated form.)
struct.error: 'I' format requires 0 <= number <= 4294967295
when I tried your code.c_outer[inner_index:inner_index+4] = struct.pack('Q', id(outer))
withValueError: Can only assign sequence of same size
+4
with+8
. EDIT: I've updated the linked Gist and it should now work on both 32-bit and 64-bit platforms.internal_print
(aroundobject.c:315
andtupleprint
(aroundtupleobject.c:253
). The problem of recursive container reprs was fixed in Python 3.2: bugs.python.org/issue9840