Is it safe to import a module multiple times?

I was interested in this for a while: is it safe to import the module several times? Of course, if a module runs operating systems, such as writing to files or something else, then probably not, but for most simple modules, is it safe to simply perform a willy-nilly import? Is there an agreement that defines the global state of the module?

+7
source share
2 answers

Yes, you can import module as many times as you want in a single Python program, no matter what module it is. Each subsequent import after the first access to the cached module instead of re-evaluation.

+16
source

Importing an os module under ten thousand different names does not cause any problems.

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

When importing to different classes:

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

Both work without problems. Of course, this is not a guarantee, but at least it seems that you are not faced with immediate practical problems.

+3
source

All Articles