Coverage for /home/runner/.local/share/hatch/env/virtual/importnb/KA2AwMZG/test.stdlib/lib/python3.9/site-packages/importnb/entry_points.py: 78%

39 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-11-02 04:02 +0000

1import sys 1bcdef

2from contextlib import contextmanager, ExitStack 1bcdef

3 

4# See compatibility note on `group` 

5# https://docs.python.org/3/library/importlib.metadata.html#entry-points 

6if sys.version_info < (3, 10): 6 ↛ 9line 6 didn't jump to line 9, because the condition on line 6 was never false1bcdef

7 from importlib_metadata import entry_points 1bcdef

8else: 

9 from importlib.metadata import entry_points 

10 

11 

12__all__ = ("imports",) 1bcdef

13ENTRY_POINTS = dict() 1bcdef

14 

15 

16def get_importnb_entry_points(): 1bcdef

17 """discover the known importnb entry points""" 

18 global ENTRY_POINTS 

19 for ep in entry_points(group="importnb"): 1a

20 ENTRY_POINTS[ep.name] = ep.value 1a

21 return ENTRY_POINTS 1a

22 

23 

24def loader_from_alias(alias): 1bcdef

25 """load an attribute from a module using the entry points value specificaiton""" 

26 from importlib import import_module 1a

27 from operator import attrgetter 1a

28 

29 module, _, member = alias.rpartition(":") 1a

30 module = import_module(module) 1a

31 return attrgetter(member)(module) 1a

32 

33 

34def loader_from_ep(alias): 1bcdef

35 """discover a loader for an importnb alias or vaue""" 

36 if ":" in alias: 36 ↛ 37line 36 didn't jump to line 37, because the condition on line 36 was never true1a

37 return loader_from_alias(alias) 

38 

39 if not ENTRY_POINTS: 1a

40 get_importnb_entry_points() 1a

41 

42 if alias in ENTRY_POINTS: 42 ↛ 45line 42 didn't jump to line 45, because the condition on line 42 was never false1a

43 return loader_from_alias(ENTRY_POINTS[alias]) 1a

44 

45 raise ValueError(f"{alias} is not a valid loader alias.") 

46 

47 

48@contextmanager 1bcdef

49def imports(*names): 1bcdef

50 """a shortcut to importnb loaders through entrypoints""" 

51 types = set() 1a

52 with ExitStack() as stack: 1a

53 for name in names: 1a

54 t = loader_from_ep(name) 1a

55 if t not in types: 55 ↛ 53line 55 didn't jump to line 53, because the condition on line 55 was never false1a

56 stack.enter_context(t()) 1a

57 types.add(t) 1a

58 yield stack 1a

59 

60 

61def list_aliases(): 1bcdef

62 """list the entry points associated with importnb""" 

63 if not ENTRY_POINTS: 

64 get_importnb_entry_points() 

65 return list(ENTRY_POINTS)