Total Complexity | 2 |
Total Lines | 51 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import atexit |
||
2 | from contextlib import ExitStack |
||
3 | from pathlib import Path |
||
4 | |||
5 | try: |
||
6 | from importlib.resources import path, read_binary |
||
7 | except ImportError: |
||
8 | from importlib_resources import path, read_binary # type: ignore |
||
9 | |||
10 | try: |
||
11 | from importlib.metadata import distribution as get_distribution |
||
12 | except ImportError: |
||
13 | from importlib_metadata import distribution as get_distribution |
||
14 | |||
15 | # See https://importlib-resources.readthedocs.io/en/latest/migration.html#pkg-resources-resource-filename |
||
16 | _file_manager = ExitStack() |
||
17 | atexit.register(_file_manager.close) |
||
18 | |||
19 | |||
20 | def resource_filename(package: str, resource: str) -> Path: |
||
21 | """ |
||
22 | Reimplementation of the function with the same name from pkg_resources |
||
23 | |||
24 | Using importlib for better performance |
||
25 | |||
26 | package : str |
||
27 | The package from where to start looking for resource (often __name__) |
||
28 | resource : str |
||
29 | The resource to look up |
||
30 | """ |
||
31 | parent_package = package.rsplit('.',1)[0] |
||
32 | return _file_manager.enter_context(path(parent_package, resource)) |
||
33 | |||
34 | |||
35 | def resource_string(package: str, resource: str) -> bytes: |
||
36 | """ |
||
37 | Reimplementation of the function with the same name from pkg_resources |
||
38 | |||
39 | Using importlib for better performance |
||
40 | |||
41 | package : str |
||
42 | The package from where to start looking for resource (often __name__) |
||
43 | resource : str |
||
44 | The resource to look up |
||
45 | """ |
||
46 | parent_package = package.rsplit('.',1)[0] |
||
47 | return read_binary(parent_package, resource) |
||
48 | |||
49 | |||
50 | __all__ = ['resource_filename', 'resource_string', 'get_distribution'] |
||
51 |