Show More
@@ -1,62 +1,50 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | A simple utility to import something by its string name. |
|
4 | 4 | |
|
5 | 5 | Authors: |
|
6 | 6 | |
|
7 | 7 | * Brian Granger |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | # Copyright (C) 2008-2011 The IPython Development Team |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | # Functions and classes |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | def import_item(name): |
|
22 | 22 | """Import and return ``bar`` given the string ``foo.bar``. |
|
23 | 23 | |
|
24 | 24 | Calling ``bar = import_item("foo.bar")`` is the functional equivalent of |
|
25 | 25 | executing the code ``from foo import bar``. |
|
26 | 26 | |
|
27 | 27 | Parameters |
|
28 | 28 | ---------- |
|
29 | 29 | name : string |
|
30 | 30 | The fully qualified name of the module/package being imported. |
|
31 | 31 | |
|
32 | 32 | Returns |
|
33 | 33 | ------- |
|
34 | 34 | mod : module object |
|
35 | 35 | The module that was imported. |
|
36 | 36 | """ |
|
37 | ||
|
38 | package = '.'.join(name.split('.')[0:-1]) | |
|
39 | obj = name.split('.')[-1] | |
|
40 | 37 | |
|
41 | # Note: the original code for this was the following. We've left it | |
|
42 | # visible for now in case the new implementation shows any problems down | |
|
43 | # the road, to make it easier on anyone looking for a problem. This code | |
|
44 | # should be removed once we're comfortable we didn't break anything. | |
|
45 | ||
|
46 | ## execString = 'from %s import %s' % (package, obj) | |
|
47 | ## try: | |
|
48 | ## exec execString | |
|
49 | ## except SyntaxError: | |
|
50 | ## raise ImportError("Invalid class specification: %s" % name) | |
|
51 | ## exec 'temp = %s' % obj | |
|
52 | ## return temp | |
|
53 | ||
|
54 | if package: | |
|
55 | module = __import__(package,fromlist=[obj]) | |
|
38 | parts = name.rsplit('.', 1) | |
|
39 | if len(parts) == 2: | |
|
40 | # called with 'foo.bar....' | |
|
41 | package, obj = parts | |
|
42 | module = __import__(package, fromlist=[obj]) | |
|
56 | 43 | try: |
|
57 | 44 | pak = module.__dict__[obj] |
|
58 | 45 | except KeyError: |
|
59 | 46 | raise ImportError('No module named %s' % obj) |
|
60 | 47 | return pak |
|
61 | 48 | else: |
|
62 | return __import__(obj) | |
|
49 | # called with un-dotted string | |
|
50 | return __import__(parts[0]) |
General Comments 0
You need to be logged in to leave comments.
Login now