What happens when you import a module?
summary
Explains exactly how import works: Python checks sys.modules cache, walks sys.meta_path finders (pathfinder, builtins, frozen), gets a ModuleSpec, uses the spec’s loader (or importlib.util) to create a module object and exec source into its __dict__; modules always execute on import and .pyc caching speeds later loads. Demonstrates pitfalls like local random.py shadowing stdlib, shows counts: interactive 79 modules, IPython 646, Jupyter 1020, and uses importlib.import_module and exec to implement loading.
AI-written summary · about
chapters (26)
- 0:00Introduction to Reuben
- 1:02Why modules matter
- 2:51What is a module?
- 4:22Import statement basics
- 5:53Module objects and attributes
- 7:16Handling circular imports
- 8:26The module cache
- 10:42Pseudo code for imports
- 12:40Importing as aliases
- 14:11Global variables and namespaces
- 16:09From-import statement
- 17:15From-import pseudo code
- 18:51Risks of import star
- 19:55Functional importing
- 21:05How Python finds modules
- 24:35Modifying sys.path
- 26:39Finders and loaders
- 28:22Sys.metapath
- 30:46Built-in and compiled modules
- 32:37Module caching and pyc files
- 33:45Exec and module attributes
- 35:33Module execution process
- 37:20Dangers of eval and exec
- 39:22Populating the module namespace
- 41:59Import summary
- 43:33Packages and conclusion
related talks
26mWhat happens behind execution of an `import` statement?
28mImport Deep Dive
30mImporting Without "import": Behind the Scenes of importlib
21mHacking the Python Import System
29m"from where?!? import what?!?"
23mEverything is a Python module
26mModules 101: how to avoid spaghetti, big balls of mud and houses of straw!
23mHooking into the import system
