Skip to content

Use Field(default=value) instead of Field(value) #3069

@Gara-Dorta

Description

@Gara-Dorta

Describe the bug
Pylance fails to understand that the fields have default values and complains about uninitialised attributes. This is described in microsoft/pylance-release#3115 and this section in the pydantic documentation https://docs.pydantic.dev/latest/integrations/visual_studio_code/#adding-a-default-with-field.

To Reproduce

Example schema:

https://datamodel-code-generator.koxudaxi.dev/#1-create-a-schema-file

Used commandline:

https://datamodel-code-generator.koxudaxi.dev/#2-run-the-generator

Expected behavior

The default values use the keyword default= when assigning the value:

# generated by datamodel-codegen:
#   filename:  tutorial_pet.json

from __future__ import annotations

from enum import Enum
from typing import Optional

from pydantic import BaseModel, Field


class Species(Enum):
    dog = 'dog'
    cat = 'cat'
    bird = 'bird'
    fish = 'fish'


class Pet(BaseModel):
    name: str = Field(..., description="The pet's name")
    species: Species
    age: Optional[int] = Field(default=None, description='Age in years', ge=0)
    vaccinated: Optional[bool] = False

Version:

  • OS: Ubuntu 24.04
  • Python version: 3.12.3
  • datamodel-code-generator version: 0.55.0

Additional context

I think it is safe to change the default behaviour to always use default=. If not, at least it'd be great to have a flag to enable it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions