Skip to content

Instantly share code, notes, and snippets.

@rctay
Created June 29, 2010 07:42
Show Gist options
  • Save rctay/456934 to your computer and use it in GitHub Desktop.
Save rctay/456934 to your computer and use it in GitHub Desktop.
[python] import with a string
def import_obj(str):
"""
Import an object with dotted name ``str``.
Use cases:
- ``import_obj('foo.Bar')`` - equivalent to ``from foo import Bar``.
- ``import_obj('Bar')`` - gets the object 'Bar' from the global symbol
table.
"""
try:
i = str.rindex('.')
obj_str = str[i+1:]
mod_str = str[:i]
except ValueError:
# no dot; treat it as a global
obj = globals().get(str, None)
if not obj:
# we use ImportError to keep error handling for callers simple
raise ImportError
return obj
else:
mod = __import__(mod_str, globals(), locals(), [obj_str])
return getattr(mod, obj_str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment