Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 When are imports loaded?
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?

(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.
def foo_func():
    return f'i am {foo_func.__name__}'
import foo

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

if __name__ == '__main__':
I am bar,hello also to <i am foo_func>
λ ptpython 
λ ptpython -i
>>> 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 
>>> import sys

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

# So when call module foo in bar it's --> 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 was instead:


def bar_func():
    print(f'I am bar,hello also to <{foo.foo_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 -
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures


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)