Created
July 24, 2019 15:51
-
-
Save podhmo/176ca9de9e47a04e98af78a54a621a62 to your computer and use it in GitHub Desktop.
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
import textwrap | |
import sys | |
from importlib.machinery import ModuleSpec | |
# todo: typed | |
class DummyImporter: # importer = finder + loader | |
@classmethod | |
def find_spec(cls, fullname, path=None, target=None): | |
loader = cls | |
return ModuleSpec(fullname, loader) | |
@classmethod | |
def create_module(cls, spec): | |
return None | |
@classmethod | |
def exec_module(cls, module): | |
code = textwrap.dedent( | |
""" | |
def hello(): | |
return f"hello from {__name__}" | |
""" | |
) | |
exec(code, module.__dict__) | |
sys.meta_path.append(DummyImporter) | |
# execしても良いけれど既存のものをそのまま使いたいなー。 | |
import xxx # noqa | |
print(xxx.hello()) | |
import yyy # noqa | |
print(yyy.hello()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment