You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi,
I want to use pydantic to store main settings and per-host settings.
The host settings should inherit their default values from the main settings.
If I manipulate the main settings, the changes should automatically propagate to the host settings as long as the fields are not explicitly set to anything but None.
I was trying to use validators, but they seem to set the value and when I change the nested main config, the change doesn't get propagated.
Isn't there something that would allow me modifying the returned value from a field while keeping the stored value intact?
Any ideas?
Example code:
from pydantic import *
from typing import *
class MainConfig(BaseModel):
verbose: bool = Field(default=False)
class HostConfig(BaseModel):
model_config = ConfigDict(
extra="forbid",
validate_assignment=True,
validate_default=True,
validate_return=True,
)
main_config: MainConfig = Field()
hostname: str = Field()
verbose: Optional[bool] = Field(default=None)
main = MainConfig()
assert main.verbose == False
host = HostConfig(main_config=main, hostname="example.com", verbose=None)
assert host.verbose == False
# ^^^ if host.verbose is None, I want to return main_config.verbose instead
# when main.verbose changes, host.verbose follows
main.verbose = True
assert host.verbose == True
# when host.verbose != None, return the explicitly set value
host.verbose = False
main.verbose = True
assert host.verbose == False
# when host.verbose == None, return the inherited value again
host.verbose = None
main.verbose = True
assert host.verbose == True
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hi,
I want to use pydantic to store main settings and per-host settings.
The host settings should inherit their default values from the main settings.
If I manipulate the main settings, the changes should automatically propagate to the host settings as long as the fields are not explicitly set to anything but
None
.I was trying to use validators, but they seem to set the value and when I change the nested main config, the change doesn't get propagated.
Isn't there something that would allow me modifying the returned value from a field while keeping the stored value intact?
Any ideas?
Example code:
Beta Was this translation helpful? Give feedback.
All reactions