2

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.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
tMC
  • 18,105
  • 14
  • 62
  • 98
  • 2
    `__init__()` is called when objects are created. If your import creates objects, your code is actually doing things in a very bad way. Please provide some code so you can see -- and fix -- your problem. – S.Lott May 18 '11 at 01:20
  • i haven't created anything yet- i wondering if i put defs in a file named, MyMod.py and import MyMod, how can MyMod tell if it was `import MyMod` or `reload(MyMod)` – tMC May 18 '11 at 01:23
  • 1
    What? defs have nothing to do with creation of objects and invocation of the `__init__` special method. What on earth are you talking about? – S.Lott May 18 '11 at 01:58

2 Answers2

3

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.

David Z
  • 128,184
  • 27
  • 255
  • 279
0
>>> import os
>>> os.foo = 5
>>> os.foo
5
>>> import os
>>> os.foo
5
quasistoic
  • 4,657
  • 1
  • 17
  • 10
  • if you `reload(os)` is there a way to tell (from within os) if it had been `import`ed or `reload()`ed – tMC May 18 '11 at 01:27
  • I misunderstood the question. See David Zaslavsky's answer. In general you don't really want to be maintaining state within your module - it's usually considered bad practice. – quasistoic May 18 '11 at 01:44
  • http://stackoverflow.com/questions/6024799/python-object-persistence-over-re-execs – tMC May 18 '11 at 01:51