Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created July 24, 2019 15:51
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 podhmo/176ca9de9e47a04e98af78a54a621a62 to your computer and use it in GitHub Desktop.
Save podhmo/176ca9de9e47a04e98af78a54a621a62 to your computer and use it in GitHub Desktop.
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