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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

15 statements  

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 __future__ import annotations 

7 

8from typing import Any 

9 

10 

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

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

13 

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

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

16 

17 Parameters 

18 ---------- 

19 name : string 

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

21 

22 Returns 

23 ------- 

24 mod : module object 

25 The module that was imported. 

26 """ 

27 if not isinstance(name, str): 

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

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

30 if len(parts) == 2: 

31 # called with 'foo.bar....' 

32 package, obj = parts 

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

34 try: 

35 pak = getattr(module, obj) 

36 except AttributeError as e: 

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

38 return pak 

39 else: 

40 # called with un-dotted string 

41 return __import__(parts[0])