zmievsa / pydantic-duality

Automatically and lazily generate three versions of your pydantic models: one with Extra.forbid, one with Extra.ignore, and one with all fields optional
https://ovsyanka83.github.io/pydantic-duality/
MIT License
31 stars 1 forks source link

Annotations of types from `typing` are not resolved recursively causing "forbid" behavior for __response__ #10

Closed r4victor closed 2 weeks ago

r4victor commented 8 months ago

python-duality recursively resolves annotations like A | B, list[A], tuple[A], etc, but fails to resolve any of the types from typing such as Union, List, NamedTuple, etc.

Here's an example with list vs List.

from typing import List
from pydantic_duality import DualBaseModel

class A(DualBaseModel):
    one: str

class B(DualBaseModel):
    two: str
    my_list: list[A]

class C(DualBaseModel):
    two: str
    my_list: List[A]

# parses ok
B.__response__.parse_obj({
    "two": "2",
    "extra": "3",
    "my_list": [{"one": "1", "extra": "2"}]
})

# validation error despite __response__
C.__response__.parse_obj({
    "two": "2",
    "extra": "3",
    "my_list": [{"one": "1", "extra": "2"}]
})

And the traceback:

Traceback (most recent call last):
  File "broken_types.py", line 25, in <module>
    C.__response__.parse_obj({
  File "pydantic/main.py", line 526, in pydantic.main.BaseModel.parse_obj
  File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for CResponse
one
  field required (type=value_error.missing)

This is because GenericAlias annotations are all handled in _resolve_annotation(): https://github.com/zmievsa/pydantic-duality/blob/4027d106cb5604e234fecfc43a5a60a5f15137aa/pydantic_duality/__init__.py#L33

but none of the typing types are.

There are a lot of types to be handled. This can certainly be done on a one-by-one basis. I'm not sure if there is a generic way to do that.

zmievsa commented 8 months ago

Yup. Makes sense. I've already solved this problem in some of my other libraries such as Cadwyn. Will take care of it soon.

zmievsa commented 2 weeks ago

Sorry for being away for so long. I came back to fix it.

Update: Seems like it's alright in the latest version. I guess we just forgot to close it. I'll close it but feel free to reopen it if the issue is not fixed for you.