Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to importlib.resources to load package resources #49

Open
klamann opened this issue Jul 8, 2021 · 1 comment
Open

Switch to importlib.resources to load package resources #49

klamann opened this issue Jul 8, 2021 · 1 comment

Comments

@klamann
Copy link
Contributor

klamann commented Jul 8, 2021

currently we're using pkg_resources to load resource files like the default.conf. Since Python 3.7, there is the importlib.resources module in the standard library, which provides a more convenient and efficient way to access resources.

Only problem is that we're currently compatible with Python 3.6; should we make >=3.7 a requirement or leave this for now? The benefit is not huge, but support for Python 3.6 will end this year anyway.

We can probably replace the current implementation with

from importlib.abc import Traversable
from importlib.resources import files

def get_resource_string(path: str) -> str:
    """
    Load a package resource (i.e. a file from within this package)

    :param path: the path, starting at the root of the current module (e.g. 'res/default.conf').
           must be a string, not a Path object!
    :return: the contents of the resource file as string
    """
    return get_resource_path(path).read_text()


def get_resource_bytes(path: str) -> bytes:
    """
    Load a package resource (i.e. a file from within this package)

    :param path: the path, starting at the root of the current module (e.g. 'res/image.png').
           must be a string, not a Path object!
    :return: the contents of the resource file as bytes
    """
    return get_resource_path(path).read_bytes()


def get_resource_path(path: Union[str, Traversable]) -> Traversable:
    """Get a reference to a package internal path object"""
    module_name = __name__.split('.')[0]
    return files(module_name).joinpath(path)
@klamann
Copy link
Contributor Author

klamann commented Jul 8, 2021

I just noticed that importlib.resources.files is only available in Python >=3.9 and the functions available since 3.7, well they suck. So I think we can keep pkg_resources until Python 3.9 becomes the min version for at-python-template...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant