Skip to content

Instantly share code, notes, and snippets.

@achillesrasquinha
Created June 12, 2019 21:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achillesrasquinha/920f0f51389a52651ea9e76040089a31 to your computer and use it in GitHub Desktop.
Save achillesrasquinha/920f0f51389a52651ea9e76040089a31 to your computer and use it in GitHub Desktop.
Import into Python via String

Handles

  • import foobar
  • import foo.bar as baz
  • from foo import bar
  • from foo.bar import Baz
  • from foo.bar import BAZ
class HandlerRegistry(dict):
    def __missing__(self, name):
        if '.' not in name:
            handler = __import__(name)
        else:
            module_name, handler_name = name.rsplit('.', 1)

            module = __import__(module_name, {}, {}, [handler_name])
            handler = getattr(module, handler_name)

            self[name] = handler

        return handler

_HANDLER_REGISTRY = HandlerRegistry()

def import_handler(name):
    handler = _HANDLER_REGISTRY[name]
    return handler

To Use

>>> Sequence = import_handler('collections.Sequence')
>>> ndarray  = import_handler('numpy.ndarray')
>>> now      = import_handler('datetime.datetime.now')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment