Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How safe is it to import a module multiple times? [duplicate]

Tags:

python

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?

like image 804
alexgolec Avatar asked Sep 19 '12 01:09

alexgolec


People also ask

What happens if I import the same module twice?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.

What happens when you import a module multiple times Python?

So each module is imported only one time. To better understand import mechanics I would suggest to create toy example. So import really happens only once. You can adjust this toy example to check cases that are interesting to you.

Can you import same module twice in Python?

In fact, Python only loads the module when it is imported in the first file and all subsequent files simply set the name to refer to the already loaded module. While it is possible to override this behavior so that each file has its own copy of the module, it is generally not recommended.

Can two modules import each other?

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names, if placed at the top level of a module (outside any functions or classes), are added to the module's global namespace.


1 Answers

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.

like image 169
nneonneo Avatar answered Oct 30 '22 13:10

nneonneo