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

1 import sys 6 ctx 1bcdefg

2 from contextlib import contextmanager, ExitStack 6 ctx 1bcdefg

3

4# See compatibility note on `group`

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

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

7 from importlib_metadata import entry_points 6 ctx 1bcdefg

8 else:

9 from importlib.metadata import entry_points

10

11

12 __all__ = ("imports",) 6 ctx 1bcdefg

13 ENTRY_POINTS = dict() 6 ctx 1bcdefg

14

15

16 def get_importnb_entry_points(): 6 ctx 1bcdefg

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

18 global ENTRY_POINTS

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

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

21 return ENTRY_POINTS 1 ctx 1a

22

23

24 def loader_from_alias(alias): 6 ctx 1bcdefg

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

26 from importlib import import_module 1 ctx 1a

27 from operator import attrgetter 1 ctx 1a

28

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

30 module = import_module(module) 1 ctx 1a

31 return attrgetter(member)(module) 1 ctx 1a

32

33

34 def loader_from_ep(alias): 6 ctx 1bcdefg

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 true 1 ctx 1a

37 return loader_from_alias(alias)

38

39 if not ENTRY_POINTS: 1 ctx 1a

40 get_importnb_entry_points() 1 ctx 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 false 1 ctx 1a

43 return loader_from_alias(ENTRY_POINTS[alias]) 1 ctx 1a

44

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

46

47

48@contextmanager 6 ctx 1bcdefg

49 def imports(*names): 6 ctx 1bcdefg

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

51 types = set() 1 ctx 1a

52 with ExitStack() as stack: 1 ctx 1a

53 for name in names: 1 ctx 1a

54 t = loader_from_ep(name) 1 ctx 1a

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

56 stack.enter_context(t()) 1 ctx 1a

57 types.add(t) 1 ctx 1a

58 yield stack 1 ctx 1a

59

60

61 def list_aliases(): 6 ctx 1bcdefg

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

63 if not ENTRY_POINTS:

64 get_importnb_entry_points()

65 return list(ENTRY_POINTS)