Skip to content

Pydantic "Not Recognizing" Field in BaseModel with Default Value of Type #2213

@ntenenz

Description

@ntenenz

Checks

  • [X ] I added a descriptive title to this issue
  • [X ] I have searched (google, github) for similar issues and couldn't find anything
  • [X ] I have read and followed the docs and still think this is a bug

Bug

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

pydantic version: 1.7.3
pydantic compiled: True
python version: 3.8.2 (default, Mar 13 2020, 10:14:16)  [GCC 9.3.0]
platform: Linux-4.19.128-microsoft-standard-x86_64-with-glibc2.29
optional deps. installed: ['typing-extensions']
import pydantic
from typing import Type, Sequence, Union

class T:
    pass

class Model(pydantic.BaseModel):
    t: Union[Type[T], Sequence[Type[T]]] = T
    
    @pydantic.validator("t", always=True)
    def make_tuple(cls, v):
        if isinstance(v, Sequence):
            return tuple(v)
        return v,

# ConfigError: Validators defined with incorrect fields: make_tuple (use check_fields=False if you're inheriting from the model and intended this)

Note: If the field is marked optional and the default value is set to None, the code works without issue.

import pydantic
from typing import Type, Sequence, Union, Optional

class T:
    pass

class Model(pydantic.BaseModel):
    t: Optional[Union[Type[T], Sequence[Type[T]]]] = None
    
    @pydantic.validator("t", always=True)
    def make_tuple(cls, v):
        if not v:
            return T,
        elif isinstance(v, Sequence):
            return tuple(v)
        return v,

Model()
# Model(t=(<class '__main__.T'>,))

Perhaps I am missing something obvious in my sleep-deprived stupor?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions