Skip to content

Mypy finds errors in the first example from the documentation #1072

@andreymal

Description

@andreymal
This example
from datetime import datetime
from typing import List
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: datetime = None
    friends: List[int] = []

external_data = {
    'id': '123',
    'signup_ts': '2019-06-01 12:22',
    'friends': [1, 2, '3']
}
user = User(**external_data)
print(user.id)
print(repr(user.signup_ts))
print(user.friends)
print(user.dict())
$ mypy --strict pydantic_example.py 
pydantic_example.py:3: error: Module 'pydantic' has no attribute 'BaseModel'
pydantic_example.py:5: error: Class cannot subclass 'BaseModel' (has type 'Any')
pydantic_example.py:8: error: Incompatible types in assignment (expression has type "None", variable has type "datetime")

This is not false positive. Pydantic __init__.py uses implicit reexport (this is an error, and I don't want to ignore it using --no-implicit-reexport), and this example uses None for a non-optional field (this is also an error).

In general, I can't trust a library that suggests putting None in a non-optional field in the very first example. This violates the mypy type system.

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