Created
June 29, 2010 07:42
-
-
Save rctay/456934 to your computer and use it in GitHub Desktop.
[python] import with a string
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
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
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