From 16da37f52edf7ac84d1d250c1d959a1f4baaf1d8 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Tue, 25 Feb 2025 17:56:29 +0000 Subject: [PATCH] Use `importlib.resources` to locate data files Following the recommendation at https://stackoverflow.com/questions/6028000/how-to-read-a-static-file-from-inside-a-python-package/58941536#58941536. This is needed to work under various unusual python runtimes. --- pyuca/collator.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pyuca/collator.py b/pyuca/collator.py index c4d20ad..4476074 100644 --- a/pyuca/collator.py +++ b/pyuca/collator.py @@ -4,7 +4,10 @@ import re import sys import unicodedata +import importlib.abc +import importlib.resources from io import open +import pathlib from .trie import Trie from .utils import hexstrings2int @@ -39,15 +42,15 @@ class BaseCollator(object): def __init__(self, filename=None): if filename is None: - filename = os.path.join( - os.path.dirname(__file__), - "allkeys-{0}.txt".format(self.UCA_VERSION)) + filename = importlib.resources.files(__package__).joinpath("allkeys-{0}.txt".format(self.UCA_VERSION)) + elif isinstance(filename, str): + filename = pathlib.Path(filename) self.table = Trie() self.implicit_weights = [] self.load(filename) def load(self, filename): - with open(filename) as keys_file: + with filename.open() as keys_file: for line in keys_file: line = line.split("#", 1)[0].rstrip()