Skip to content

Instantly share code, notes, and snippets.

@moreati
Created January 31, 2024 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moreati/44bce66fe0c4febc8d80e064532d4b49 to your computer and use it in GitHub Desktop.
Save moreati/44bce66fe0c4febc8d80e064532d4b49 to your computer and use it in GitHub Desktop.
Minimal example driving Python importlib machinery to import a runtime created module
#!/usr/bin/env python3
import importlib.machinery
import sys
import types
class Finder:
def find_spec(self, fullname, path, target=None):
if fullname != 'poc_module':
return None
spec = importlib.machinery.ModuleSpec(
fullname,
loader=Loader(),
origin='<fevered imagination>',
)
return spec
class Loader:
def create_module(self, spec):
module = types.ModuleType(spec.name)
module.__spec__ = spec
module.__loader__ = spec.loader
module.__file__ = spec.origin
return module
def exec_module(self, module):
source = 'import math; tau=2*math.pi; print("Hello importlib fans!")'
code = compile(source, module.__file__, 'exec')
exec(code, module.__dict__)
print('Inserting Finder into meta_path')
sys.meta_path.insert(0, Finder())
print('Importing poc_module')
import poc_module
print(f'{poc_module=}')
print(f'{poc_module.__spec__=}')
print(f'{poc_module.tau=}')
@moreati
Copy link
Author

moreati commented Jan 31, 2024

This Proof of Concept demonstrates a dynamically generated Python module getting imported. There is no poc_module.py on disk.

$ python3 importlib_importer_poc.py
Inserting Finder into meta_path
Importing poc_module
Hello importlib fans!
poc_module=<module 'poc_module' (<fevered imagination>)>
poc_module.__spec__=ModuleSpec(name='poc_module', loader=<__main__.Loader object at 0x1046219d0>, origin='<fevered imagination>')
poc_module.tau=6.283185307179586

The Python import machinery is (somewhat) described in https://docs.python.org/3/reference/import.html and https://docs.python.org/3/library/importlib.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment