Referencing Package Resources in Code and Tests

Correctly reference files bundled with a Python package from both application code and tests without relying on the current working directory

How do I correctly reference files bundled with a Python package from both application code and tests without relying on the current working directory?

Using importlib.resources

from importlib import resources

resource = resources.files("my_package") / "resources" / "config.json"

with resource.open("r", encoding="utf-8") as f:
    config = f.read()

For tests, reference the resource through the package that owns it rather than through the test's filesystem location:

from importlib import resources

resource = resources.files(test_resources_module) / "resources" / "data.json"

with resource.open("r", encoding="utf-8") as f:
    data = f.read()

For resources that need to be passed to an API requiring a filesystem path:

from importlib import resources

resource = resources.files(module) / "resources" / "schema.json"

with as_file(resource) as path:
    use_path(path)