Skip to content

Commit 55d3394

Browse files
committed
Merge remote-tracking branch 'kachayev/import-object'
2 parents 2744f37 + 54f56d4 commit 55d3394

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

tornado/util.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
import zlib
1818

1919

20+
import sys
21+
2022
class ObjectDict(dict):
2123
"""Makes a dictionary behave like an object, with attribute-style access.
2224
"""
@@ -63,17 +65,35 @@ def flush(self):
6365
def import_object(name):
6466
"""Imports an object by name.
6567
68+
import_object('x') is equivalent to 'import x'.
6669
import_object('x.y.z') is equivalent to 'from x.y import z'.
6770
6871
>>> import tornado.escape
6972
>>> import_object('tornado.escape') is tornado.escape
7073
True
7174
>>> import_object('tornado.escape.utf8') is tornado.escape.utf8
7275
True
76+
>>> import_object('tornado') is tornado
77+
True
78+
>>> import_object('missing_module')
79+
Traceback (most recent call last):
80+
...
81+
ImportError: No module named missing_module
82+
>>> import_object('tornado.missing_module')
83+
Traceback (most recent call last):
84+
...
85+
ImportError: No module named missing_module
7386
"""
87+
if name.count('.') == 0:
88+
return __import__(name, None, None)
89+
7490
parts = name.split('.')
7591
obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
76-
return getattr(obj, parts[-1])
92+
try:
93+
return getattr(obj, parts[-1])
94+
except AttributeError:
95+
exc_info = sys.exc_info()
96+
raise ImportError, "No module named %s" % parts[-1], exc_info[2]
7797

7898
# Fake unicode literal support: Python 3.2 doesn't have the u'' marker for
7999
# literal strings, and alternative solutions like "from __future__ import

0 commit comments

Comments
 (0)