Skip to content

schema_json() fails for optional namedtuple fields with default value #2707

@unti1x

Description

@unti1x

Checks

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

Bug

When trying to generate a schema for a model with an optional NamedTuple field which have a default value, schema_json() fails when trying to unpack parameters for the tuple:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "pydantic/main.py", line 715, in pydantic.main.BaseModel.schema_json
  File "pydantic/main.py", line 704, in pydantic.main.BaseModel.schema
  File "pydantic/schema.py", line 167, in pydantic.schema.model_schema
  File "pydantic/schema.py", line 548, in pydantic.schema.model_process_schema
  File "pydantic/schema.py", line 589, in pydantic.schema.model_type_schema
  File "pydantic/schema.py", line 234, in pydantic.schema.field_schema
  File "pydantic/schema.py", line 202, in pydantic.schema.get_field_info_schema
  File "pydantic/schema.py", line 892, in genexpr
TypeError: <lambda>() missing 1 required positional argument: 'y'
 def encode_default(dft: Any) -> Any:
     if isinstance(dft, (int, float, str)):
         return dft
     elif sequence_like(dft):
         t = dft.__class__
>        return t(encode_default(v) for v in dft)
   ...

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

             pydantic version: 1.8.1
            pydantic compiled: True
                 install path: /venv/lib/python3.9/site-packages/pydantic
               python version: 3.9.0+ (default, Oct 20 2020, 08:43:38)  [GCC 9.3.0]
                     platform: Linux-5.4.0-72-generic-x86_64-with-glibc2.31
     optional deps. installed: ['dotenv', 'typing-extensions']
from typing import List, Optional, NamedTuple
from pydantic import BaseModel


class Coordinates(NamedTuple):
    x: float
    y: float


class LocationBase(BaseModel):
    name: str
    coords: Optional[Coordinates] = Coordinates(0, 0)
    zoom: Optional[int] = 10


LocationBase.schema_json()

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