Passed
Push — master ( bd7aec...0c6208 )
by Konstantin
02:28
created

ocrd_utils.package_resources   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 2
eloc 21
dl 0
loc 51
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A resource_string() 0 13 1
A resource_filename() 0 13 1
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