[Python] How to make Pylance and Pydantic understand each other when instantiating BaseModel...

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to instantiate user = User(**external_data), where User is Pydantic BaseModel, but I am getting error from Pylance, which don't like my external_data dictionary and unable to figure out that data in the dict is actually correct (see first screenshot).

    [​IMG]

    I found a workaround by creating TypedDict with the same declaration as for User(BaseModel). Now Pylance is happy, but I am not, because I need to repeat myself (see second screenshot).

    [​IMG]

    Any ideas on how to make Pylance and Pydantic understand each other without repetition?

    from datetime import datetime
    from pydantic import BaseModel
    from typing import TypedDict

    class UserDict(TypedDict, total=False):
    id: int
    name: str
    signup_ts: datetime
    friends: list[int]


    class User(BaseModel):
    id: int
    name: str = "John Doe"
    signup_ts: datetime | None = None
    friends: list[int] = []


    external_data: UserDict = {
    'id': 123,
    'name': 'Vlad',
    'signup_ts': datetime.now(),
    'friends': [1, 2, 3],
    }

    user = User(**external_data)
    print(user)
    print(user.id)


    Pylance error for the case with no UserDict:

    Argument of type "int | str | datetime | list[int]" cannot be assigned to parameter "id" of type "int" in function "__init__"
    Type "int | str | datetime | list[int]" cannot be assigned to type "int"
    "datetime" is incompatible with "int"PylancereportGeneralTypeIssues
    Argument of type "int | str | datetime | list[int]" cannot be assigned to parameter "name" of type "str" in function "__init__"
    Type "int | str | datetime | list[int]" cannot be assigned to type "str"
    "datetime" is incompatible with "str"PylancereportGeneralTypeIssues
    Argument of type "int | str | datetime | list[int]" cannot be assigned to parameter "signup_ts" of type "datetime | None" in function "__init__"PylancereportGeneralTypeIssues
    Argument of type "int | str | datetime | list[int]" cannot be assigned to parameter "friends" of type "list[int]" in function "__init__"
    Type "int | str | datetime | list[int]" cannot be assigned to type "list[int]"
    "datetime" is incompatible with "list[int]"PylancereportGeneralTypeIssues
    (variable) external_data: dict[str, int | str | datetime | list[int]]

    Continue reading...

Compartilhe esta Página