Created
July 19, 2011 09:27
-
-
Save Apkawa/1091834 to your computer and use it in GitHub Desktop.
Get python object from path
This file contains hidden or 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 get_by_path(path): | |
''' | |
get python object from path | |
>>> get_by_path('os.path.join') | |
<function join at ...> | |
''' | |
spl = path.split('.') | |
mod = None | |
for n, s in enumerate(spl, start=1): | |
try: | |
mod_path = '.'.join(spl[:-n]) | |
if not mod_path: | |
return None | |
mod = __import__(mod_path, globals=globals(), locals=locals()) | |
attrs = spl[-n:] | |
break | |
except ImportError: | |
pass | |
for s in spl[1:-n]: | |
mod = getattr(mod, s) | |
attr = mod | |
for a in attrs: | |
attr = getattr(attr, a) | |
return attr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment