acres: Access Resources on Your Terms

0.5.0 · active · verified Tue Apr 14

acres is a Python library designed to simplify access to package resources, offering a consistent API for reading, filesystem access, and cached filesystem access. It addresses common pitfalls associated with `importlib.resources` by clearly delineating resource scopes and capabilities. The current version is 0.5.0, with releases occurring periodically, typically every few months, for new features, improvements, and bug fixes.

Warnings

Install

Imports

Quickstart

The quickstart demonstrates how to use `acres.Loader` to access package resources. It shows how to read text content, get a temporary file path using `as_path` (useful for operations requiring a real filesystem path), and retrieve a cached path that persists for the interpreter's lifetime. The example uses a simulated package structure.

from acres import Loader
import os

# Assuming a package structure like:
# my_package/
#   __init__.py
#   data/
#     resource.txt

# Create dummy package for demonstration
if not os.path.exists('my_package/data'):
    os.makedirs('my_package/data')
with open('my_package/data/resource.txt', 'w') as f:
    f.write('Hello from acres!')
with open('my_package/__init__.py', 'w') as f: # Ensure it's a package
    f.write('')

# The recommended way to anchor the Loader is with __spec__.name
# For a real package, you would pass `__spec__.name` from within that package.
# For this example, we'll simulate it with a string.
package_name = 'my_package'

loader = Loader(package_name)

# Read a text resource
text_content = loader.readable('data/resource.txt').read_text()
print(f"Text resource content: {text_content}")

# Access a resource as a temporary file path using a context manager
with loader.as_path('data/resource.txt') as resource_path:
    print(f"Resource path (temporary): {resource_path}")
    print(f"Content from path: {resource_path.read_text()}")

# Access a resource that exists for the interpreter's lifetime
cached_path = loader.cached('data/resource.txt')
print(f"Resource path (cached, interpreter lifetime): {cached_path}")
print(f"Content from cached path: {cached_path.read_text()}")

# Clean up dummy package
os.remove('my_package/data/resource.txt')
os.rmdir('my_package/data')
os.remove('my_package/__init__.py')
os.rmdir('my_package')

view raw JSON →