Access resources on your terms
Low maintenance activity. Last release 18 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install acresAcres: Access resources on your terms
This module provides simple, consistent access to package resources.
from acres import Loader
loader = Loader(somepkg)
res_text = loader.readable('data/some_resource.txt').read_text()
res_bytes = loader.readable('data/another_resource.bin').read_bytes()
with loader.as_path('data') as data_dir:
# data_dir is a pathlib.Path until the "with" scope closes
resource_path = loader.cached('data/another_resource.bin')
# The path pointed to by resource_path will exist until interpreter exit
Module loader
The primary use case for acres.Loader is to allow a directory module to provide access
to its resources.
Suppose you have a module structure:
src/
mypkg/
data/
resourceDir/
...
__init__.py
resource.ext
__init__.py
...
In src/mypkg/data/__init__.py, add:
'''Data package
.. autofunction:: load_resource
.. automethod:: load_resource.readable
.. automethod:: load_resource.as_path
.. automethod:: load_resource.cached
'''
from acres import Loader
load_resource = Loader(__spec__.name)
mypkg.data.load_resource() is now a function that will return a Path to a
resource that is guaranteed to exist until interpreter exit:
from mypkg.data import load_resource
resource_file: Path = load_resource('resource.ext')
For additional control, you can use load_resource.readable() to return a Path-like
object that implements .read_text() and .read_bytes():
resource_contents: bytes = load_resource.readable('resource.ext').read_bytes()
Or a context manager with a limited lifetime:
with load_resource.as_path('resourceDir') as resource_dir:
# Work with the contents of `resource_dir` as a `Path`
# Outside the `with` block, `resource_dir` may no longer point to an existing path.
Note that load_resource() is a shorthand for load_resource.cached(),
whose explicitness might be more to your taste.