Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "import safe" mean in Python?

I just hit the behaviour where nose will not run tests marked as executable (as described in a previous question). I found this surprising, and I wasted some time trying to find out why nose wasn't running my tests before I learned about nose's behaviour here.

In the manpage for nosetests, it describes an option to override the default behaviour:

--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 non-import-safe module? And can a non-import-safe module be made import-safe by removing the executable bit, or is there more to it than that?

like image 987
Philip Potter Avatar asked Apr 26 '12 09:04

Philip Potter


People also ask

How do you fix an import error in Python?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .

What does it mean to import in Python?

Importing refers to allowing a Python file or a Python module to access the script from another Python file or module. You can only use functions and properties your program can access. For instance, if you want to use mathematical functionalities, you must import the math package first.

What are subpackages in Python?

The four modules ( mod1.py , mod2.py , mod3.py , and mod4.py ) are defined as they were before. But now, instead of being lumped together into the pkg directory, they are split out into two subpackage directories: sub_pkg1 and sub_pkg2 .


1 Answers

I'm not familiar with nose, but I'm pretty sure what it means by "import safe" is that importing the module will just define things, not go off and run stuff.

The idea would be that if a .py file is designed to be executed as a script, then its functionality will be initiated while executing module-scope code. This could be guarded against importing with the __name__ == '__main__' trick, but it might not be. If it isn't, importing it will probably do the same thing it would do as a script when invoked with no arguments, which in some cases could be bad.

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

like image 70
Ben Avatar answered Sep 19 '22 18:09

Ben