Loading Resources from Python Packages

programming, Python

Start with importlib_resources

Start with the package importlib_resources.

Properly export modules

In order for a resource to be accessible, the module (or most likely the submodule) containing it needs to be properly exported. By properly exported I mean to adding the submodule containing the resource inside the setup.py.

In this case, I wanted to make a JSON file (answers.json) accessible from a submodule (v8ball.van) of the package vans-eightball:

v8ball
  van
    answers.json
    ...

To export the submodule, the packages property in the setup.py file needs to include “v8ball.van” in order for the resource answers.json to be exported and accessible:

setup(
name="vans-eightball",
version="0.0.2",
...
packages=["v8ball.van", "v8ball"],
include_package_data=True,
...
)

Accessing the resource

An example of accessing the resource:

Install the package

pip install vans-eightball

Accessing the resource

import json
import v8ball.van
from importlib_resources import files
resource_path = files(v8ball.van).joinpath('answers.json')
data = json.loads(resource_path.read_text())