Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 When are imports loaded?
#1
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.
Quote
#2
(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'
Quote
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  external refs by libraries loaded with cdll caldodge 0 101 Jul-01-2019, 10:26 PM
Last Post: caldodge
  How Do I Get the IDE to Find My Imports petec 18 1,081 Feb-24-2019, 02:50 AM
Last Post: petec
  Nested Imports CanadaGuy 4 476 Nov-08-2018, 12:20 AM
Last Post: CanadaGuy
  check imports Viesturs 6 914 Jul-28-2018, 09:58 AM
Last Post: perfringo
  Do you require imports used in other files? Panda 1 528 Jul-14-2018, 02:30 PM
Last Post: gontajones
  global variables, classes, imports Skaperen 16 4,208 Mar-02-2017, 11:05 PM
Last Post: ichabod801

Forum Jump:


Users browsing this thread: 1 Guest(s)