Created
January 21, 2015 06:04
-
-
Save Ivlyth/c92f61a04a64f91ae9c1 to your computer and use it in GitHub Desktop.
import_object [ from tornado ]
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 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