I'm trying to get the following behavior with pydantic.BaseModel
:
class MyClass:
def __init__(self, value: T) -> None:
self._value = value
# Maybe:
@property
def value(self) -> T:
return self._value
# Maybe:
@value.setter
def value(self, value: T) -> None:
# ...
self._value = value
If T
is also a pydantic model, then recursive initialization using dictionaries should work:
# Initialize `x._value` with `T(foo="bar", spam="ham")`:
x = MyClass(value={"foo": "bar", "spam": "ham"})
Note that _value
is initialized using the kwargs value
. Validation must also be available for private fields.
The pydantic docs (PrivateAttr
, etc.) seem to imply that pydantic will never expose private attributes. I'm sure there is some hack for this. But is there an idiomatic way to achieve the behavior in pydantic? Or should I just use a custom class?