why does sys.stdout = None work?

2020-02-06 06:38发布

问题:

i can silence and restore sys.stdout this way:

import sys
sys.stdout = None
print('hello')  # does not write to stdout
sys.stdout = sys.__stdout__
print('hello')  # writes to stdout

i know i'd better be using contextlib.redirect_stdout which probably does something similar but my question is: why does the above code work?

i'd have assumed python would call things like sys.stdout.write() so whatever i replace sys.stdout with should have a write method (like e.g. io.StringIO) at least.

回答1:

print has an explicit check for None.

    /* sys.stdout may be None when FILE* stdout isn't connected */
    if (file == Py_None)
        Py_RETURN_NONE;