Skip to content

Commit 54f56d4

Browse files
committed
import_object will raise standard ImportError even in case of Value/Attribute error
1 parent 5d1ce40 commit 54f56d4

File tree

1 file changed

+19
-20
lines changed

1 file changed

+19
-20
lines changed

tornado/util.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Miscellaneous utility functions."""
22

3+
import sys
4+
35
class ObjectDict(dict):
46
"""Makes a dictionary behave like an object."""
57
def __getattr__(self, name):
@@ -18,35 +20,32 @@ def import_object(name):
1820
import_object('x') is equivalent to 'import x'.
1921
import_object('x.y.z') is equivalent to 'from x.y import z'.
2022
21-
It will return None in case of failed import operation.
22-
2323
>>> import tornado.escape
2424
>>> import_object('tornado.escape') is tornado.escape
2525
True
2626
>>> import_object('tornado.escape.utf8') is tornado.escape.utf8
2727
True
2828
>>> import_object('tornado') is tornado
2929
True
30-
>>> import_object('tornado.missing_module') is None
31-
True
32-
>>> import_object('missing_module') is None
33-
True
30+
>>> import_object('missing_module')
31+
Traceback (most recent call last):
32+
...
33+
ImportError: No module named missing_module
34+
>>> import_object('tornado.missing_module')
35+
Traceback (most recent call last):
36+
...
37+
ImportError: No module named missing_module
3438
"""
35-
def safe_import(*args, **kwargs):
36-
try:
37-
return __import__(*args, **kwargs)
38-
except ImportError:
39-
return None
40-
4139
if name.count('.') == 0:
42-
return safe_import(name, None, None)
43-
else:
44-
parts = name.split('.')
45-
obj = safe_import('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
46-
try:
47-
return getattr(obj, parts[-1])
48-
except AttributeError:
49-
return None
40+
return __import__(name, None, None)
41+
42+
parts = name.split('.')
43+
obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
44+
try:
45+
return getattr(obj, parts[-1])
46+
except AttributeError:
47+
exc_info = sys.exc_info()
48+
raise ImportError, "No module named %s" % parts[-1], exc_info[2]
5049

5150
# Fake byte literal support: In python 2.6+, you can say b"foo" to get
5251
# a byte literal (str in 2.x, bytes in 3.x). There's no way to do this

0 commit comments

Comments
 (0)