17

I've been wondering this for a while: Is it guaranteed to be safe to import a module multiple times? Of course, if the module performs operating systems things like write to files or something, then probably not, but for the majority of simple modules, is it safe to simply perform imports willy-nilly? Is there a convention that governs the global state of a module?

alexgolec
  • 26,898
  • 33
  • 107
  • 159
  • I don't know about how safe it is to import a module multiple times, but I don't see why you would do that, why not just use `imp.reload`? – Nick Beeuwsaert Sep 19 '12 at 02:00
  • 1
    Good news is (as you can see in the question of which this is a duplicate) that no matter how many times you import a module, the import will happen only once – David Robinson Sep 19 '12 at 02:01

2 Answers2

41

Yes, you can import module as many times as you want in one Python program, no matter what module it is. Every subsequent import after the first accesses the cached module instead of re-evaluating it.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
10

Importing the os module under ten thousand different names doesn't seem to give any problems.

for i in range(10000):
    exec("import os as foo%i" % i)

for i in range(10000):
    exec("foo%i.getcwd()" % i)

With the imports in different classes:

for i in range(10000):
    exec("""class FooClass%i:
    import os as foo%i
    print foo%i.getcwd()""" % (i,i,i))

Both run without problems. Not a guarantee of course, but at least it appears you don't run into immediate practical problems.

Junuxx
  • 14,011
  • 5
  • 41
  • 71