-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Closed
Labels
Description
Bug
Please complete:
- OS: Mac OS
- Python version
import sys; print(sys.version): 3.6.7 with dataclasses backport - Pydantic version
import pydantic; print(pydantic.VERSION): 1.0
It is known that @pydantic.dataclasses.dataclass doesn't fully mimic the BaseModel. However, we'd like use .schema() representation faithfully. I'm wondering what's the best workaround.
Adding a Config for b with required=False doesn't carry over to .schema() either.
from typing import Dict
from dataclasses import field
from pydantic import Field, ValidationError
from pydantic.dataclasses import dataclass
@dataclass
class D1:
a: int
# b: Dict[str, int] = {"x":10} # mutable default, not allowed
@dataclass
class D2:
a: int
b: Dict[str, int] = Field({"x":10}) # pydantic.Field, unsafe and invalid default
@dataclass
class D3:
a: int
b: Dict[str, int] = field(default_factory=lambda: {"x":10}) # std lib, safe and invalid default
class C:
fields = {"b": { "required": False}} # doesn't carry over!!
@dataclass(config=C)
class D4:
a: int
b: Dict[str, int] = field(default_factory=lambda: {"x":10})
print(D1(10))
try:
print(D2(10))
except ValidationError as e:
print(e) # pydantic/dataclasses.py:77
print(D3(10))
req = D3.__pydantic_model__.schema()["required"]
if req != ["a"]:
print('only ["a"] should be required, is:', req)
print()
print(D4.__pydantic_model__.schema()["required"]) # same as D3Output
D1(a=10)
1 validation error for D2
b
value is not a valid dict (type=type_error.dict)
D3(a=10, b={'x': 10})
only ["a"] should be required, is: ['a', 'b']
['a', 'b']