I am storing settings in json file > loading it > using eval to evaluate the stringified data.
However I am sure eval is not the best way to do it.
I would like to know if there is any better way to implement it without using eval. Any pointer will be a great help.
Below is what I have got now.
Store the settings - decision_settings.json
{
"DecisionModelConfig": {
"model_type": "ModelType.RULE_BASED",
"model_path": "DECISION_MODEL_PATH"
}
}
Load the settings - abc.py
with open("decision_settings.json", encoding="utf-8") as settings:
decision_settings = json.load(settings)
Use eval to evaluate the stringified
input as read from json file
from abc.settings import decision_settings
from abc_pqr import ModelType
from abc_xyz import DECISION_MODEL_PATH
class DecisionModelConfig(BaseModel):
model_type: ModelType = eval(decision_settings["DecisionModelConfig"]["model_type"])
model_path: Path = eval(pipeline_decision_settings["DecisionModelConfig"]["model_path"])
class ModelType(str, Enum):
RULE_BASED = "rule based"
MACHINE_LEARNING = "machine learning"
DECISION_MODEL_PATH = PROJECT_DIR / "models" / "whatever.json"
-- EDIT --
This is what we intend to have:
class DecisionModelConfig(BaseModel):
model_type: ModelType = ModelType.RULE_BASED
model_path: Path = DECISION_MODEL_PATH
This is what we get if we directly use the dict keys(without eval on it) - we get the deserialized data in form of string
class DecisionModelConfig(BaseModel):
model_type: ModelType = "ModelType.RULE_BASED"
model_path: Path = "DECISION_MODEL_PATH"
Using eval however evaluates the string and we are good.