Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Created January 21, 2015 06:04
Show Gist options
  • Save Ivlyth/c92f61a04a64f91ae9c1 to your computer and use it in GitHub Desktop.
Save Ivlyth/c92f61a04a64f91ae9c1 to your computer and use it in GitHub Desktop.
import_object [ from tornado ]
def import_object(name):
"""Imports an object by name.
import_object('x') is equivalent to 'import x'.
import_object('x.y.z') is equivalent to 'from x.y import z'.
>>> import tornado.escape
>>> import_object('tornado.escape') is tornado.escape
True
>>> import_object('tornado.escape.utf8') is tornado.escape.utf8
True
>>> import_object('tornado') is tornado
True
>>> import_object('tornado.missing_module')
Traceback (most recent call last):
...
ImportError: No module named missing_module
"""
if name.count('.') == 0:
return __import__(name, None, None)
parts = name.split('.')
obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
try:
return getattr(obj, parts[-1])
except AttributeError:
raise ImportError("No module named %s" % parts[-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment