'recursion in sys.displayhook in Python
I was checking the sys.displayhook()'s document, there is a pseudo-code there:
def displayhook(value):
if value is None:
return
# Set '_' to None to avoid recursion
builtins._ = None
text = repr(value)
try:
sys.stdout.write(text)
except UnicodeEncodeError:
bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(bytes)
else:
text = bytes.decode(sys.stdout.encoding, 'strict')
sys.stdout.write(text)
sys.stdout.write("\n")
builtins._ = value
I understood how it works but there is a comment there that is ambiguous for me. It says # Set '_' to None to avoid recursion. After I delete builtins._ = None line, I didn't see any difference:
>>> import sys, builtins
>>>
>>> def displayhook(value):
... print("displayhook called")
... if value is None:
... return
... text = repr(value)
... try:
... sys.stdout.write(text)
... except UnicodeEncodeError:
... bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
... if hasattr(sys.stdout, 'buffer'):
... sys.stdout.buffer.write(bytes)
... else:
... text = bytes.decode(sys.stdout.encoding, 'strict')
... sys.stdout.write(text)
... sys.stdout.write("\n")
... builtins._ = value
...
>>> sys.displayhook = displayhook
>>>
>>>
>>> a = 10
>>> a
displayhook called
10
>>> _
displayhook called
10
>>> builtins._
displayhook called
10
>>> b = None
>>> b
displayhook called
>>> _
displayhook called
10
>>> repr(a)
displayhook called
'10'
I was not be able to reproduce recursion and I have no idea about what recursion is it talking about. Could you tell me in which situation does the recursion occur?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
