mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
fix: pydantic dataclass can inherit from stdlib dataclass and arbitrary_types_allowed is supported (#2051)
* fix: pydantic dataclasses can inherit from stdlib dataclasses closes #2042 * docs: add some documentation * fix: support arbitrary_types_allowed with stdlib dataclass closes #2054 * docs: add documentation for custom types
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import dataclasses
|
||||
|
||||
import pydantic
|
||||
|
||||
|
||||
class ArbitraryType:
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def __repr__(self):
|
||||
return f'ArbitraryType(value={self.value!r})'
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class DC:
|
||||
a: ArbitraryType
|
||||
b: str
|
||||
|
||||
|
||||
# valid as it is a builtin dataclass without validation
|
||||
my_dc = DC(a=ArbitraryType(value=3), b='qwe')
|
||||
|
||||
try:
|
||||
class Model(pydantic.BaseModel):
|
||||
dc: DC
|
||||
other: str
|
||||
|
||||
Model(dc=my_dc, other='other')
|
||||
except RuntimeError as e: # invalid as it is now a pydantic dataclass
|
||||
print(e)
|
||||
|
||||
|
||||
class Model(pydantic.BaseModel):
|
||||
dc: DC
|
||||
other: str
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
|
||||
m = Model(dc=my_dc, other='other')
|
||||
print(repr(m))
|
||||
@@ -0,0 +1,27 @@
|
||||
import dataclasses
|
||||
|
||||
import pydantic
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class Z:
|
||||
z: int
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class Y(Z):
|
||||
y: int = 0
|
||||
|
||||
|
||||
@pydantic.dataclasses.dataclass
|
||||
class X(Y):
|
||||
x: int = 0
|
||||
|
||||
|
||||
foo = X(x=b'1', y='2', z='3')
|
||||
print(foo)
|
||||
|
||||
try:
|
||||
X(z='pika')
|
||||
except pydantic.ValidationError as e:
|
||||
print(e)
|
||||
Reference in New Issue
Block a user