variable
variable

Reputation: 9684

Does using 'import module_name' statement in a function cause the module to be reloaded?

I know that when we do 'import module_name', then it gets loaded only once, irrespective of the number of times the code passes through the import statement.

But if we move the import statement into a function, then for each function call does the module get re-loaded? If not, then why is it a good practice to import a module at the top of the file, instead of in function?

Does this behavior change for a multi threaded or multi process app?

Upvotes: 0

Views: 59

Answers (3)

An0n1m1ty
An0n1m1ty

Reputation: 458

It doesn't get reloaded after every function call and threading does not change this behavior. Here's how I tested it:

test.py:

print("Loaded")

testing.py:

import _thread

def call():
    import test

for i in range(10):
    call()

_thread.start_new_thread(call, ())
_thread.start_new_thread(call, ())

OUTPUT:

LOADED

To answer your second question, if you import the module at the top of the file, the module will be imported for all functions within the python file. This saves you from having to import the same module in multiple functions if they use the same module.

Upvotes: 2

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

I know that when we do 'import module_name', then it gets loaded only once, irrespective of the number of times the code passes through the import statement.

Right!


But if we move the import statement into a function, then for each function call does the module get re-loaded?

No. But if you want, you can explicitly do it something like this:

import importlib
importlib.reload(target_module)

If not, then why is it a good practice to import a module at the top of the file, instead of in function?

When Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the existing module object as is.

Even though it does not get reloaded, still it has to check if this module is already imported or not. So, there is some extra work done each time the function is called which is unnecessary.

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71580

It does not get loaded every time.

Proof:

file.py:

print('hello')

file2.py:

def a():
    import file
a()
a()

Output:

hello

Then why put it on the top?:

Because writing the imports inside a function will cause calls to that function take longer.

Upvotes: 2

Related Questions