importlib Imports Modules By Dotted Name
Load a module by dotted name with importlib, reload it in place, and inspect a spec with find_spec without executing the module.
Code
import importlib
import importlib.util
import sys
import tempfile
from pathlib import Path
def main() -> None:
with tempfile.TemporaryDirectory() as tmp:
module_path = Path(tmp) / 'inventory.py'
module_path.write_text(
'STOCK = {"bolt": 12}\n\n'
'def count(sku):\n'
' return STOCK.get(sku, 0)\n',
encoding='utf-8',
)
sys.path.insert(0, tmp)
try:
module = importlib.import_module('inventory')
print('module file:', Path(module.__file__).name)
print('count:', module.count('bolt'))
print('reload keeps object:', importlib.reload(module) is module)
finally:
sys.path.remove(tmp)
sys.modules.pop('inventory', None)
# find_spec 只探测模块位置,不执行模块代码
spec = importlib.util.find_spec('json')
print('json spec found:', spec is not None)
print('json origin:', Path(spec.origin).name if spec and spec.origin else None)
if __name__ == '__main__':
main()How it works
Count the functions main and count as the entire surface area of importlib Imports Modules By Dotted Name.
From importlib it pulls Path — the imports name exactly which library surface the snippet touches.
Points of care
- Plan for an install step:
importlibis a real dependency, resolved by the package manager.
Applying it
Look for the module file:, count:, reload keeps object: prefixes when the file runs; they tie each line to its step.
Launch the file; main takes over and steps through count.
Interactive Tools for This Topic
CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `importlib`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.