Permalink
Browse files

Merge remote-tracking branch 'kachayev/import-object'

  • Loading branch information...
2 parents 2744f37 + 54f56d4 commit 55d33945abc89a3ad7783e6c2ccc6ef44909008c @bdarnell bdarnell committed Apr 14, 2013
Showing with 21 additions and 1 deletion.
  1. +21 −1 tornado/util.py
View
22 tornado/util.py
@@ -17,6 +17,8 @@
import zlib
+import sys
+
class ObjectDict(dict):
"""Makes a dictionary behave like an object, with attribute-style access.
"""
@@ -63,17 +65,35 @@ def flush(self):
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('missing_module')
+ Traceback (most recent call last):
+ ...
+ ImportError: No module named missing_module
+ >>> 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)
- return getattr(obj, parts[-1])
+ try:
+ return getattr(obj, parts[-1])
+ except AttributeError:
+ exc_info = sys.exc_info()
+ raise ImportError, "No module named %s" % parts[-1], exc_info[2]
# Fake unicode literal support: Python 3.2 doesn't have the u'' marker for
# literal strings, and alternative solutions like "from __future__ import

0 comments on commit 55d3394

Please sign in to comment.