All inclusive with importlib.resources
An issue I had to deal with recently was how to access a package resource (e.g., a JSON file) when you never know exactly where that named resource will wind up on the local file system, especially when installing into a virtual environment from a package index like PyPI. Wouldn't it be nice to allow your package some introspection so that it can magically find (and read) the resource regardless of where it is installed on the local file system? Enter importlib.resources
.
In the following example, a resource file named rules.json
, which lives in the metapype.eml
package, is read as text and returned to rules
as string variable. All in one step. Say no more.
rules = importlib.resources.read_text("metapype.eml", "rules.json")
Note that importlib.resources
has a few more really handy introspective methods you should check out.