3
3
from typing import List , Dict , Any
4
4
5
5
import pandas as pd
6
- import pkg_resources
7
6
import yaml
8
7
9
8
@@ -28,8 +27,7 @@ def print_anes_mapping():
28
27
29
28
"""
30
29
mapping = load_yaml ('anes-mapping.yaml' )
31
- df = pd .read_csv (pkg_resources .resource_filename (
32
- __name__ , 'data/anes_pilot_2024_20240319.csv' ))
30
+ df = pd .read_csv (get_resource_path (__name__ , 'data/anes_pilot_2024_20240319.csv' ))
33
31
for key in mapping .keys ():
34
32
details = mapping [key ]
35
33
@@ -79,7 +77,7 @@ def load_yaml(file_path: str) -> Dict[str, Any]:
79
77
Returns:
80
78
A dictionary containing the contents of the YAML file.
81
79
"""
82
- full_path = pkg_resources . resource_filename (__name__ , file_path )
80
+ full_path = get_resource_path (__name__ , file_path )
83
81
if not os .path .exists (full_path ):
84
82
raise FileNotFoundError (
85
83
f"The file { full_path } does not exist. Please ensure the file path is correct." )
@@ -219,3 +217,35 @@ def format(self, avoid_double_period=True, **kwargs):
219
217
f"{ value } ." , value )
220
218
221
219
return formatted_string
220
+
221
+
222
+ def get_resource_path (package : str , resource : str ) -> str :
223
+ """
224
+ Get the path to a resource file, supporting both pkg_resources and importlib.resources.
225
+ Falls back to importlib.resources if pkg_resources is not available.
226
+
227
+ Problem this solves:
228
+ - In python 3.12, pkg_resources is being deprecated in favor of importlib.resources, and
229
+ it no longer comes with pkg_resources. This creates an import error unless user does `pip install setuptools` but it is
230
+ bad practice to add setuptools as a runtime dependency.
231
+
232
+ - If I just switch to importlib, this is limiting since importlib is only for 3.9+.
233
+
234
+ - So the solution is to use pkg_resources if available, and if not, use importlib.resources.
235
+
236
+
237
+ Args:
238
+ package: The package name (just __name__ usually)
239
+ resource: The resource path relative to the package
240
+
241
+ Returns:
242
+ str: The full path to the resource
243
+ """
244
+ try :
245
+ import pkg_resources
246
+ return pkg_resources .resource_filename (package , resource )
247
+ except ImportError :
248
+ from importlib import resources
249
+ root_package = package .split ('.' )[0 ]
250
+ with resources .path (root_package , resource ) as path :
251
+ return str (path )
0 commit comments