What does import safe mean in Python?

I just hit the behavior when the nose does not run tests marked as executable (as described in the previous question ). I found this unexpected, and I spent a bit of time figuring out why the nose didn't pass my tests before I found out about the behavior of the nose here.

In the man page for nosetests, he describes an option to override the default behavior:

--exe Look for tests in python modules that are executable. Normal behavior is to exclude executable modules, since they may not be import-safe [NOSE_INCLUDE_EXE] 

My question is: what does import-safe mean? What is an example of a module not requiring import? And can a safe import be a safe module to be safe for import by deleting the executable bit, or is it bigger than this?

+6
source share
3 answers

I am not familiar with the nose, but I am sure that this means that the “import is safe” is that importing the module will simply determine things, and not leave and run the material.

The idea would be that if the .py file is intended to be executed as a script, then its functionality will be triggered when the module's scope code is executed. This may be protected from import with the __name__ == '__main__' trick, but it may not be. If this is not the case, importing will probably do the same thing as in the case of the script when called without arguments, which in some cases can be bad.

So, you can directly say that there are no such executable scripts that can be dangerous to import by passing the --exe flag, or you can clear the executable permission from your scripts.

+5
source

"import-safe" does not have a specific, specific meaning. In this case, the fact is that Python modules can do something when they are imported (remember that importing a module simply means executing it and storing all things in its namespace).

If the module is marked with an executable bit, nose assumes that it is, and since you probably do not want this material to appear every time you run your tests, it skips the module.

+5
source

This applies to modules that can be imported or executed as a script. This is usually done using the following code snippet:

 if __name__ == "__main__": print "running as script" 

If the script that was supposed to be executable does not have this check, the import will execute it immediately, which is likely to result in unwanted side effects or an raised exception.

+4
source

Source: https://habr.com/ru/post/914203/


All Articles