为什么 sys.stdout = None 有效?

why does sys.stdout = None work?

我可以这样沉默和恢复sys.stdout

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

我知道我最好使用 contextlib.redirect_stdout,它可能会做类似的事情,但我的问题是:为什么上面的代码有效?

我假设 python 会调用 sys.stdout.write() 这样的东西,所以无论我用 sys.stdout 替换什么都应该有一个 write 方法(比如 io.StringIO) 至少。

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;