1
1
"""Miscellaneous utility functions."""
2
2
3
+ import sys
4
+
3
5
class ObjectDict (dict ):
4
6
"""Makes a dictionary behave like an object."""
5
7
def __getattr__ (self , name ):
@@ -18,35 +20,32 @@ def import_object(name):
18
20
import_object('x') is equivalent to 'import x'.
19
21
import_object('x.y.z') is equivalent to 'from x.y import z'.
20
22
21
- It will return None in case of failed import operation.
22
-
23
23
>>> import tornado.escape
24
24
>>> import_object('tornado.escape') is tornado.escape
25
25
True
26
26
>>> import_object('tornado.escape.utf8') is tornado.escape.utf8
27
27
True
28
28
>>> import_object('tornado') is tornado
29
29
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
34
38
"""
35
- def safe_import (* args , ** kwargs ):
36
- try :
37
- return __import__ (* args , ** kwargs )
38
- except ImportError :
39
- return None
40
-
41
39
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 ]
50
49
51
50
# Fake byte literal support: In python 2.6+, you can say b"foo" to get
52
51
# a byte literal (str in 2.x, bytes in 3.x). There's no way to do this
0 commit comments