Coverage for /home/runner/.local/share/hatch/env/virtual/importnb/KA2AwMZG/test.interactive/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:03 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-02 04:03 +0000
1import sys 1bcdefg
2from contextlib import contextmanager, ExitStack 1bcdefg
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 false1bcdefg
7 from importlib_metadata import entry_points 1bcdefg
8else:
9 from importlib.metadata import entry_points
12__all__ = ("imports",) 1bcdefg
13ENTRY_POINTS = dict() 1bcdefg
16def get_importnb_entry_points(): 1bcdefg
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
24def loader_from_alias(alias): 1bcdefg
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
29 module, _, member = alias.rpartition(":") 1a
30 module = import_module(module) 1a
31 return attrgetter(member)(module) 1a
34def loader_from_ep(alias): 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 true1a
37 return loader_from_alias(alias)
39 if not ENTRY_POINTS: 1a
40 get_importnb_entry_points() 1a
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
45 raise ValueError(f"{alias} is not a valid loader alias.")
48@contextmanager 1bcdefg
49def imports(*names): 1bcdefg
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
61def list_aliases(): 1bcdefg
62 """list the entry points associated with importnb"""
63 if not ENTRY_POINTS:
64 get_importnb_entry_points()
65 return list(ENTRY_POINTS)