Skip to content

Instantly share code, notes, and snippets.

@etrepum
Created March 15, 2014 15:57
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 etrepum/9569467 to your computer and use it in GitHub Desktop.
Save etrepum/9569467 to your computer and use it in GitHub Desktop.
Implementing CPython import as a function
## This is the implementation of the terrible hack
from sys import _getframe
from importlib import import_module
def import_(name, as_=None, globals_=None):
as_ = as_ or name.partition('.')[0]
globals_ = globals_ or _getframe(1).f_globals
globals_[as_] = import_module(name)
## This is what usage looks like:
import_('json')
print json.dumps(["don't", "do", "this!"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment