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


Messages In This Thread
When are imports loaded? - by MuntyScruntfundle - Feb-10-2019, 12:54 PM
RE: When are imports loaded? - by snippsat - Feb-10-2019, 01:40 PM
RE: When are imports loaded? - by ichabod801 - Feb-10-2019, 03:47 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Is Matplotlib.pyplot Loaded DaveG 2 1,332 Apr-06-2022, 06:12 AM
Last Post: DaveG
  Imports that work with Python 3.8 fail with 3.9 and 3.10 4slam 1 2,602 Mar-11-2022, 01:50 PM
Last Post: snippsat
  Package cannot be loaded into PBS queue file emersonpl 1 1,840 Sep-09-2021, 08:06 PM
Last Post: emersonpl
  PyQt5 MySQL Drivers Not Loaded AdeS 7 5,091 Aug-06-2021, 08:34 AM
Last Post: AdeS
  Imports in my first package cuppajoeman 1 1,966 Jun-28-2021, 09:06 AM
Last Post: snippsat
  script with imports works but pytest gives "ModuleNotFoundError"? Hpao 0 1,578 Jun-27-2021, 08:30 PM
Last Post: Hpao
  Help wanted with python imports petros21 3 2,581 Apr-07-2021, 07:16 PM
Last Post: snippsat
Question How to include Modules not found (conditional imports) in my setup.py when I want to cff 0 3,838 Mar-17-2021, 11:57 AM
Last Post: cff
  MacOS BigSur Python3 - dyld: Library not loaded: trillionanswers 1 4,221 Mar-02-2021, 11:00 PM
Last Post: nilamo
  Why is mpl_toolkits loaded? Gribouillis 1 1,621 Jan-30-2021, 08:39 PM
Last Post: Serafim

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020