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

14 statements  

« prev     ^ index     » next       coverage.py v7.3.3, created at 2023-12-15 06:13 +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. 

6from typing import Any 

7 

8 

9def import_item(name: str) -> Any: 

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

11 

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

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

14 

15 Parameters 

16 ---------- 

17 name : string 

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

19 

20 Returns 

21 ------- 

22 mod : module object 

23 The module that was imported. 

24 """ 

25 if not isinstance(name, str): 

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

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])