Skip to content

Commit 7b97b22

Browse files
Merge pull request #862 from padraic-shafer/pkg-assets
Transition the import of package files
2 parents 199e0de + 8d07d30 commit 7b97b22

File tree

1 file changed

+41
-5
lines changed

1 file changed

+41
-5
lines changed

databroker/assets/base_registry.py

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
from . import core
1212
import warnings
1313
from ..utils import ensure_path_exists
14-
from pkg_resources import resource_filename
1514
import json
1615
from .utils import _ChainMap
1716
from .handlers_base import DuplicateHandler
@@ -20,6 +19,45 @@
2019
logger = logging.getLogger(__name__)
2120

2221

22+
@contextmanager
23+
def open_resource_file(
24+
package: str, # ModuleType
25+
resource: str, # os.PathLike
26+
):
27+
"""Context manager to open a resource file.
28+
29+
Parameters
30+
----------
31+
package : str (ModuleType)
32+
The package containing the resource.
33+
resource : str (os.PathLike)
34+
The resource to open.
35+
36+
Yields
37+
------
38+
file : TextIO
39+
A text file-like object for the resource.
40+
"""
41+
use_importlib = True
42+
try:
43+
from importlib.resources import as_file, files
44+
except ImportError: # pragma: no cover
45+
try:
46+
from importlib_resources import as_file, files
47+
except ImportError: # pragma: no cover
48+
from pkg_resources import resource_filename
49+
use_importlib = False
50+
51+
if use_importlib:
52+
with as_file(files(package) / resource) as path:
53+
with open(path, 'r', encoding='utf-8') as fin:
54+
yield fin
55+
else:
56+
path = resource_filename(package, resource)
57+
with open(path, 'r', encoding='utf-8') as fin:
58+
yield fin
59+
60+
2361
class BaseRegistryRO(object):
2462
"""This is the base-class for asset registries.
2563
@@ -75,11 +113,9 @@ def DatumNotFound(self):
75113
base_name = 'schemas/'
76114
resource_name = '{}{}_resource.json'.format(base_name, spec_name)
77115
datum_name = '{}{}_datum.json'.format(base_name, spec_name)
78-
with open(resource_filename('databroker.assets',
79-
resource_name), 'r') as fin:
116+
with open_resource_file('databroker.assets', resource_name) as fin:
80117
tmp_dict['resource'] = json.load(fin)
81-
with open(resource_filename('databroker.assets',
82-
datum_name), 'r') as fin:
118+
with open_resource_file('databroker.assets', datum_name) as fin:
83119
tmp_dict['datum'] = json.load(fin)
84120
KNOWN_SPEC[spec_name] = tmp_dict
85121

0 commit comments

Comments
 (0)