Python Forum

Full Version: When are imports loaded?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
If I have code that imports a couple of libraries I've put together, do they load to memory when the main thread starts, or when there is an actual call to the library?

Reason for asking, .I run my code and the app starts quickly, but there is a quite a pause when the libraries are first actioned.

So if I want an immediate response every time I call a library I have to make a dummy call before my processing actually begins.

Is this correct, or am I missing something about the import commands?

Thanks.
(Feb-10-2019, 12:54 PM)MuntyScruntfundle Wrote: [ -> ]do they load to memory when the main thread starts, or when there is an actual call to the library?
Importing a module/package will always be fully imported into sys.modules mapping.
So the file/files with imported code will always be there even if you call it or not.
Eg:
# foo.py
def foo_func():
    return f'i am {foo_func.__name__}'
# bar.py
import foo

def bar_func():
    print(f'I am bar,hello also to <{foo.foo_func()}>')

if __name__ == '__main__':
    bar_func()
Output:
I am bar,hello also to <i am foo_func>
λ ptpython 
λ ptpython -i bar.py
>>> dir()
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'bar_func', 'foo', 're', 'run', 'sys']

# See that foo is also here,also the file foo.py 
>>> import sys

>>> sys.modules['foo']
<module 'foo' from 'E:\\div_code\\import_test\\foo.py'>

# So when call module foo in bar it's foo.py --> foo_func()
>>> sys.modules['foo'].foo_func()
'i am foo_func'
But in terms of timing, the module is not loaded until the import statement. If bar.py was instead:

# bar.py

def bar_func():
    print(f'I am bar,hello also to <{foo.foo_func()}>')

bar_func()

import foo
You would get a name error when you tried tried to call bar_func, because foo is not loaded at that point.