1 # encoding: utf-8 2 """ 3 A simple utility to import something by its string name. 4 """ 5 6 # Copyright (c) IPython Development Team. 7 # Distributed under the terms of the Modified BSD License. 8 9 10 def import_item(name): 11 """Import and return ``bar`` given the string ``foo.bar``. 12 13 Calling ``bar = import_item("foo.bar")`` is the functional equivalent of 14 executing the code ``from foo import bar``. 15 16 Parameters 17 ---------- 18 name : string 19 The fully qualified name of the module/package being imported. 20 21 Returns 22 ------- 23 mod : module object 24 The module that was imported. 25 """ 26 27 parts = name.rsplit('.', 1) 28 if len(parts) == 2: 29 # called with 'foo.bar....' 30 package, obj = parts 31 module = __import__(package, fromlist=[obj]) 32 try: 33 pak = getattr(module, obj) 34 except AttributeError as e: 35 raise ImportError('No module named %s' % obj) from e 36 return pak 37 else: 38 # called with un-dotted string 39 return __import__(parts[0]) 40