Skip to content

Instantly share code, notes, and snippets.

@Apkawa
Created July 19, 2011 09:27
Show Gist options
  • Save Apkawa/1091834 to your computer and use it in GitHub Desktop.
Save Apkawa/1091834 to your computer and use it in GitHub Desktop.
Get python object from path
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