Skip to content

mypy error on default_factory=list in pydantic 1.10 #4457

@tapple

Description

@tapple

Initial Checks

  • I have searched GitHub for a duplicate issue and I'm sure this is something new
  • I have searched Google & StackOverflow for a solution and couldn't find anything
  • I have read and followed the docs and still think this is a bug
  • I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like FastAPI or mypy)

Description

mypy complains about default_factory = list in pydantic 1.10

But using [] works fine. I think this inconsistency should be fixed

$ mypy bug.py
bug.py:6: error: Incompatible types in assignment (expression has type "List[_T]", variable has type "List[str]")
Found 1 error in 1 file (checked 1 source file)

Also, I don't think the documentation indicates that pydantic deep-copies mutable default values. I found that out at https://stackoverflow.com/questions/63793662/how-to-give-a-pydantic-list-field-a-default-value

Example Code

from typing import List
from pydantic import BaseModel, Field


class Model(BaseModel):
    l1: List[str] = Field(default_factory=list)
    l2: List[str] = Field([])
    l3: List[str] = []

Python, Pydantic & OS Version

pydantic version: 1.10.1
            pydantic compiled: True
                 install path: /home/mfulmer/miniconda3/envs/rk310/lib/python3.10/site-packages/pydantic
               python version: 3.10.4 (main, Mar 31 2022, 08:41:55) [GCC 7.5.0]
                     platform: Linux-5.4.0-124-generic-x86_64-with-glibc2.31
     optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions']

Affected Components

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