From sys import stderr or import sys → sys.stderr

To describe a standard error output stream in Python code

from sys import stderr 

stderr

And how to write

import sys

sys.stderr

There are two ways to write. Not just stderr, but all imports. Well, how to use them properly. Aside from the fact that the former has slightly better performance when used in a loop, there is a semantic difference.

--In the former, the reference to stderr is confirmed when this module is loaded. --For the latter, the reference is not fixed until you call sys.stderr.

What happens is that when you try to replace the output destination using contextlib.redirect_stderr for unit testing, in the former case if the module is already loaded, the reference to stderr is confirmed ** replacement Does not work **. In the latter case, stderr is acquired from sys only when the process is executed, so ** replacement is effective **.

Since the plain print function can be turned with contextlib.redirect_stdout, it can be said that it is the operation to get stdout from sys on the spot every time, so if you want to match the behavior to this, please describe the latter. It means that it should be done.

Recommended Posts

From sys import stderr or import sys → sys.stderr
Python from or import
from sklearn.datasets import fetch_mldata-> fetch_openml