|
17 | 17 | import zlib
|
18 | 18 |
|
19 | 19 |
|
| 20 | +import sys |
| 21 | + |
20 | 22 | class ObjectDict(dict):
|
21 | 23 | """Makes a dictionary behave like an object, with attribute-style access.
|
22 | 24 | """
|
@@ -63,17 +65,35 @@ def flush(self):
|
63 | 65 | def import_object(name):
|
64 | 66 | """Imports an object by name.
|
65 | 67 |
|
| 68 | + import_object('x') is equivalent to 'import x'. |
66 | 69 | import_object('x.y.z') is equivalent to 'from x.y import z'.
|
67 | 70 |
|
68 | 71 | >>> import tornado.escape
|
69 | 72 | >>> import_object('tornado.escape') is tornado.escape
|
70 | 73 | True
|
71 | 74 | >>> import_object('tornado.escape.utf8') is tornado.escape.utf8
|
72 | 75 | 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 |
73 | 86 | """
|
| 87 | + if name.count('.') == 0: |
| 88 | + return __import__(name, None, None) |
| 89 | + |
74 | 90 | parts = name.split('.')
|
75 | 91 | 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] |
77 | 97 |
|
78 | 98 | # Fake unicode literal support: Python 3.2 doesn't have the u'' marker for
|
79 | 99 | # literal strings, and alternative solutions like "from __future__ import
|
|
0 commit comments