Philip Potter Philip Potter - 2 months ago 6x
Python Question

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?

Ben Ben

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.