I am implementing runtime configuration for a python package. I am doing this in mypkg.config.__init__.py
. The idea is to load the configuration from a JSON file into a ConfigManagerClass that uses a Pydantic model to validate and store the configuration. The ConfigManager lets users of the package update the config from another JSON file of their choice when needed.
Here's the code:
"""Runtime configuration for the package."""
import importlib.resources as pkg_resources
import json
from mypkg.pydantic.schemas import RuntimeConfigSchema
class RuntimeConfigManager():
with pkg_resources.open_text('mypkg.config', 'default.json') as f:
_config_json = json.load(f)
print('Loading default config')
_config = RuntimeConfigSchema(**_config_json)
print('Config loaded')
@classmethod
def set_config_file(cls, config_file):
"""Update runtime config from file."""
print(f'Updating config from {config_file}')
with open(config_file, 'r') as f:
cls._config_json = json.load(f)
cls._config = RuntimeConfigSchema(**cls._config_json)
print('Config updated')
@classmethod
def get_config(cls):
"""Get current runtime config."""
return cls._config
Is this idiomatic? Are there any failure cases to be aware of? The package is compatible with Python >=3.8.10, <3.10