@@ -6,11 +6,10 @@ The `importlib` module provides tools for importing modules and working with Pyt
66
77| Operation | Time | Space | Notes |
88| -----------| ------| -------| -------|
9- | ` import_module(name) ` | O(n) | O(n) | n = import depth |
10- | ` find_loader(name) ` | O(1) | O(1) | Check sys.modules |
11- | ` reload(module) ` | O(n) | O(n) | n = module size |
12- | ` import_module(package) ` | O(n+m) | O(n+m) | n = submodules |
13- | ` resources.files() ` | O(1) | O(1) | Get resource path |
9+ | ` import_module(name) ` | Varies | Varies | Depends on cache, meta path, and I/O |
10+ | ` importlib.util.find_spec(name) ` | Varies | Varies | Depends on finders and file system |
11+ | ` reload(module) ` | Varies | Varies | Re-executes module code |
12+ | ` resources.files(package) ` | Varies | Varies | May import package or access loaders |
1413
1514## Common Operations
1615
@@ -19,17 +18,17 @@ The `importlib` module provides tools for importing modules and working with Pyt
1918``` python
2019import importlib
2120
22- # O(n) where n = import depth/module size
21+ # Cost depends on loaders, cache, and filesystem
2322# Prefer this over __import__()
2423module = importlib.import_module(' os.path' )
2524
2625# Equivalent to: import os.path
27- import_module(' json' ) # O(n)
28- import_module(' collections.abc' ) # O(n)
26+ import_module(' json' )
27+ import_module(' collections.abc' )
2928
30- # From cached sys.modules if already imported - O(1)
29+ # From cached sys.modules if already imported
3130module = importlib.import_module(' json' )
32- module = importlib.import_module(' json' ) # Second call is O(1)
31+ module = importlib.import_module(' json' ) # Second call is cached
3332```
3433
3534### Reloading Modules
@@ -38,7 +37,6 @@ module = importlib.import_module('json') # Second call is O(1)
3837import importlib
3938import mymodule
4039
41- # O(n) where n = module size
4240# Re-executes module code
4341importlib.reload(mymodule)
4442
@@ -52,33 +50,31 @@ importlib.reload(mymodule)
5250import importlib.util
5351import sys
5452
55- # O(1) - check if module is cached
5653spec = importlib.util.find_spec(' json' )
5754if spec is not None :
58- print (f " Found: { spec.origin} " ) # O(1)
55+ print (f " Found: { spec.origin} " )
5956
60- # Get loader - O(1) if cached, O(n) if needs import
57+ # Get loader
6158loader = spec.loader
6259
63- # Manual import from spec - O(n )
60+ # Manual import from spec (executes module code )
6461module = importlib.util.module_from_spec(spec)
6562sys.modules[spec.name] = module
66- spec.loader.exec_module(module) # O(n)
63+ spec.loader.exec_module(module)
6764```
6865
6966### Working with Submodules
7067
7168``` python
7269import importlib
7370
74- # O(n) where n = total submodules
7571package = importlib.import_module(' email' )
7672
77- # Get submodule - O(m) where m = submodule size
73+ # Get submodule
7874mime = importlib.import_module(' email.mime' )
7975text = importlib.import_module(' email.mime.text' )
8076
81- # Check if submodule exists - O(1) after first import
77+ # Check if submodule exists after first import
8278import email.mime.text
8379print (' email.mime.text' in sys.modules) # O(1)
8480```
@@ -92,12 +88,12 @@ import importlib
9288import sys
9389
9490def try_import (module_name , default = None ):
95- """ Safely import module - O(n) or O(1) """
91+ """ Safely import module; cost depends on cache and loaders. """
9692 try :
97- if module_name in sys.modules: # O(1) check
93+ if module_name in sys.modules: # Cached
9894 return sys.modules[module_name]
9995
100- return importlib.import_module(module_name) # O(n)
96+ return importlib.import_module(module_name)
10197 except ImportError :
10298 return default
10399
@@ -122,7 +118,7 @@ class PluginManager:
122118 self .plugins = {}
123119
124120 def load_plugin (self , name , module_path ):
125- """ Load plugin module - O(n) where n = module size """
121+ """ Load plugin module; cost depends on loaders and module code. """
126122 try :
127123 module = importlib.import_module(module_path)
128124
@@ -139,7 +135,6 @@ class PluginManager:
139135 """ Get cached plugin - O(1)"""
140136 return self .plugins.get(name)
141137
142- # Usage - O(n) per plugin
143138manager = PluginManager()
144139manager.load_plugin(' plugin1' , ' plugins.plugin1' )
145140manager.load_plugin(' plugin2' , ' plugins.plugin2' )
@@ -155,11 +150,11 @@ import importlib
155150
156151module = importlib.import_module(' collections' )
157152
158- # O(1) - hasattr checks __dict__
153+ # hasattr checks __dict__
159154if hasattr (module, ' deque' ):
160155 Deque = getattr (module, ' deque' )
161156
162- # O(n) - iterate all attributes where n = module size
157+ # iterate all attributes
163158for attr_name in dir (module): # O(n)
164159 attr = getattr (module, attr_name)
165160 if callable (attr):
@@ -172,7 +167,7 @@ for attr_name in dir(module): # O(n)
172167import importlib.util
173168
174169def module_available (name ):
175- """ Check if module can be imported - O(1) cache or O(n) search """
170+ """ Check if module can be imported; cost depends on finders. """
176171 spec = importlib.util.find_spec(name)
177172 return spec is not None
178173
@@ -181,8 +176,8 @@ available_mods = {}
181176
182177def is_available (name ):
183178 if name not in available_mods:
184- available_mods[name] = module_available(name) # O(n) first time
185- return available_mods[name] # O(1) after cached
179+ available_mods[name] = module_available(name)
180+ return available_mods[name] # Cached
186181```
187182
188183## Performance Tips
@@ -192,12 +187,12 @@ def is_available(name):
192187``` python
193188import importlib
194189
195- # Bad: O(n) import each time
190+ # Bad: import each time
196191def process ():
197192 json = importlib.import_module(' json' )
198193 return json.loads(data)
199194
200- # Good: O(1) after first import
195+ # Good: reuse cached module after first import
201196json = importlib.import_module(' json' )
202197
203198def process ():
@@ -209,7 +204,7 @@ def process():
209204``` python
210205import importlib.util
211206
212- # Efficient existence check - O(1) if cached or path-based
207+ # Efficient existence check when cached or path-based
213208if importlib.util.find_spec(' numpy' ):
214209 import numpy
215210 # Use numpy
@@ -225,22 +220,19 @@ def ensure_modules(module_list):
225220 """ Import multiple modules efficiently"""
226221 loaded = {}
227222 for name in module_list:
228- if name not in sys.modules: # O(1) check
229- loaded[name] = importlib.import_module(name) # O(n)
223+ if name not in sys.modules: # Cached check
224+ loaded[name] = importlib.import_module(name)
230225 else :
231- loaded[name] = sys.modules[name] # O(1)
226+ loaded[name] = sys.modules[name]
232227 return loaded
233228
234- # O(k*n) where k = module count, n = avg module size
229+ # Cost depends on module count, loaders, and module code
235230modules = ensure_modules([' json' , ' os' , ' sys' ])
236231```
237232
238233## Version Notes
239234
240- - ** Python 2.7** : Limited support
241- - ** Python 3.1+** : importlib added
242- - ** Python 3.4+** : importlib.util for detailed control
243- - ** Python 3.7+** : Simplified import machinery
235+ - ** Python 3.x** : ` importlib ` and ` importlib.util ` are available
244236
245237## Related Documentation
246238
0 commit comments