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.
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: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
importstatement, and a “dirty” import corresponds toreload(), becauseimportonly 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
importstatement into doing something nontrivial, or if you somehow manage to import your module for the first time usingreload(), or if you mess around with the importing mechanism (through theimpmodule 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.