Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: What is the cost of re-importing modules?

Tags:

python

import

I am often tempted to import modules in narrow contexts where they are needed. For example in the body of a function that utilises the module. In this case, the import statement may be executed many times.

Apart from stylistic issues, what is the performance cost of doing this?

like image 646
drevicko Avatar asked Apr 08 '15 01:04

drevicko


People also ask

Are imports costly Python?

There's very little cost to a repeated import statement, since Python caches modules and only imports them once (at the first import ), unless explicitly asked to reload a module with the reload function.

What happens if I import the same module twice?

If multiple modules imports the same module then angular evaluates it only once (When it encounters the module first time). It follows this condition even the module appears at any level in a hierarchy of imported NgModules.

Can we import a 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 a Python module is imported?

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.


2 Answers

There's very little cost to a repeated import statement, since Python caches modules and only imports them once (at the first import), unless explicitly asked to reload a module with the reload function. The effect (and rough performance impact) of a repeated import statement is essentially just binding the imported names in the local namespace.

It isn't completely free, however; import does have to lock and unlock the import table lock, and resolve the provided names. This means that can still slow down your program if called frequently.

like image 23
nneonneo Avatar answered Oct 17 '22 05:10

nneonneo


Take a look at the explanation on this site:

https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead

Even though Python won't import the same module multiple times, you may still have a performance hit depending on how your code is structured. You may be able to use the Timer to see what the actual impact is.

like image 197
Preston Werntz Avatar answered Oct 17 '22 03:10

Preston Werntz