跳转到主要内容

按您的条款访问资源

项目描述

Acres:按您的条款访问资源

本模块旨在提供一种简单的方式,以适应大多数用例访问包资源。

问题:`importlib.resources` 提供了一种可组合但界面丑陋的接口

from importlib.resources import files, as_file

with as_file(files(my_module) / 'data' / 'resource.ext') as resource_path:
    # Interact with resource_path as a pathlib.Path

`files()` 和 `as_file()` 函数没有明显的意义,不同的用例也没有明显映射到这些名称。

解决方案:`acres.Loader` 是一个类,它为包资源提供读取、文件系统和缓存文件系统访问。

模块数据加载器

假设您有一个模块结构

src/
  mypkg/
    data/
      resourceDir/
        ...
      __init__.py
      resource.ext
    __init__.py
    ...

src/mypkg/data/__init__.py 中,添加

'''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(__package__)

mypkg.data.load_resource 现在是一个函数,它将返回一个保证在解释器退出前存在的资源的 Path

from mypkg.data import load_resource

resource_file: Path = load_resource('resource.ext')

为了额外的控制,您可以使用 load_resource.readable() 返回一个类似于 Path 的对象,该对象实现了 .read_text().read_bytes()

resource_contents: bytes = load_resource.readable('resource.ext').read_bytes()

或一个有限生命周期的上下文管理器

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.

请注意,`load_resource()` 是 `load_resource.cached()` 的缩写,其明确性可能更适合您的口味。

按需数据加载

acres 可用作库与任何包一起使用

from acres import Loader
import somepkg

text: str = Loader(somepkg).readable('data/someresource.txt').read_text()

with Loader(somepkg).as_path('data') as somepkgdata:
    walk_dir(somepkgdata)

如果使用 Loader().cached(),则资源将保持可用,直到解释器退出,即使 Loader 实例被垃圾回收。

项目详情


下载文件

下载您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分发

acres-0.1.0.tar.gz (9.5 kB 查看哈希值)

上传时间

构建分发

acres-0.1.0-py3-none-any.whl (9.1 kB 查看哈希值)

上传时间 Python 3

支持者