Complete worked example
python
import importlib
from importlib.resources import files, as_file
import json
from pathlib import Path
import sys
from zipfile import ZipFile
def inspect_example(minimum):
archive = Path('owned.zip').resolve()
package_name = 'owned_resource_demo'
with ZipFile(archive, 'w') as bundle:
bundle.writestr(package_name + '/__init__.py', '')
bundle.writestr(package_name + '/defaults.json', json.dumps({'minimum': minimum}))
sys.path.insert(0, str(archive))
importlib.invalidate_caches()
try:
package = importlib.import_module(package_name)
resource = files(package).joinpath('defaults.json')
settings = json.loads(resource.read_text(encoding='utf-8'))
return settings
finally:
sys.path.remove(str(archive))
sys.modules.pop(package_name, None)
sys.path_importer_cache.pop(str(archive), None)- Reasoning
- The driver writes both package files into owned.zip, temporarily adds that archive to the import path and imports the named fixture. Files(package).joinpath selects defaults.json, and read_text obtains the JSON document using UTF-8. The parsed minimum is returned as an ordinary dictionary.