问题
When writing a Python module, is there a way to tell if the module is being imported or reloaded?
I know I can create a class, and the __init__()
will only be called on the first import, but I hadn't planning on creating a class. Though, I will if there isn't an easy way to tell if we are being imported or reloaded.
回答1:
The documentation for reload() actually gives a code snippet that I think should work for your purposes, at least in the usual case. You'd do something like this:
try:
reloading
except NameError:
reloading = False # means the module is being imported
else:
reloading = True # means the module is being reloaded
What this really does is detect whether the module is being imported "cleanly" (e.g. for the first time) or is overwriting a previous instance of the same module. In the normal case, a "clean" import corresponds to the import
statement, and a "dirty" import corresponds to reload()
, because import
only really imports the module once, the first time it's executed (for each given module).
If you somehow manage to force a subsequent execution of the import
statement into doing something nontrivial, or if you somehow manage to import your module for the first time using reload()
, or if you mess around with the importing mechanism (through the imp
module or the like), all bets are off. In other words, don't count on this always working in every possible situation.
P.S. The fact that you're asking this question makes me wonder if you're doing something you probably shouldn't be doing, but I won't ask.
回答2:
>>> import os
>>> os.foo = 5
>>> os.foo
5
>>> import os
>>> os.foo
5
来源:https://stackoverflow.com/questions/6038898/how-to-tell-if-a-python-modules-i-being-reloaded-from-within-the-module