tMC
tMC

Reputation: 19355

How to tell if a Python modules I being reload()ed from within the module

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.

Upvotes: 2

Views: 792

Answers (2)

David Z
David Z

Reputation: 131690

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.

Upvotes: 3

quasistoic
quasistoic

Reputation: 4687

>>> import os
>>> os.foo = 5
>>> os.foo
5
>>> import os
>>> os.foo
5

Upvotes: 0

Related Questions