Created
January 31, 2024 22:34
-
-
Save moreati/44bce66fe0c4febc8d80e064532d4b49 to your computer and use it in GitHub Desktop.
Minimal example driving Python importlib machinery to import a runtime created module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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=}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Proof of Concept demonstrates a dynamically generated Python module getting imported. There is no
poc_module.py
on disk.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