What does “import safe” mean in Python?

2019-06-20 05:33发布

问题:

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?

回答1:

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.



回答2:

"import-safe" doesn't have a specific, defined meaning. In this case, the point is that Python modules can do something when they are imported (remember, importing a module just means executing it and saving all the things in its namespace).

If the module is marked with the executable bit, nose assumes that this is the case -- and since you probably don't want that stuff to happen every time you run your tests, it will skip the module.



回答3:

It refers to modules that can be both imported or executed as a script. This is usually done by the following piece of code:

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

If a script that was meant to be executable does not have this check, importing will immediately execute it which will probably end with unwanted side effects or exception raised.