Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/traitlets/utils/importstring.py: 0%

13 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-01 06:54 +0000

1""" 

2A simple utility to import something by its string name. 

3""" 

4# Copyright (c) IPython Development Team. 

5# Distributed under the terms of the Modified BSD License. 

6 

7 

8def import_item(name): 

9 """Import and return ``bar`` given the string ``foo.bar``. 

10 

11 Calling ``bar = import_item("foo.bar")`` is the functional equivalent of 

12 executing the code ``from foo import bar``. 

13 

14 Parameters 

15 ---------- 

16 name : string 

17 The fully qualified name of the module/package being imported. 

18 

19 Returns 

20 ------- 

21 mod : module object 

22 The module that was imported. 

23 """ 

24 if not isinstance(name, str): 

25 raise TypeError("import_item accepts strings, not '%s'." % type(name)) 

26 parts = name.rsplit(".", 1) 

27 if len(parts) == 2: 

28 # called with 'foo.bar....' 

29 package, obj = parts 

30 module = __import__(package, fromlist=[obj]) 

31 try: 

32 pak = getattr(module, obj) 

33 except AttributeError as e: 

34 raise ImportError("No module named %s" % obj) from e 

35 return pak 

36 else: 

37 # called with un-dotted string 

38 return __import__(parts[0])