Search code examples
pythonpython-typingpydanticpyright

How do I get Pylance's type checking to work with this Pydantic example?


I'm discovering Pydantic and I see this in an example (https://pydantic-docs.helpmanual.io/usage/models/#recursive-models):

from pydantic import BaseModel

class Foo(BaseModel):
    count: int
    size: float = None

I'm using VS Code and Pylance, and until now, I had been ignoring Pylance's type checking functionality because I have multiple instances where I need to be able to set None as the default to a field that doesn't have None in its type annotation.

I see this in Pydantic, and Pydantic works fine with Pylance, but as is with all the other times I've tried to set a default of None to a field not annotated with None, Pylance flags it with a Expression of type "None" cannot be assigned to declared type problem.

I figure that if it's meant to work in Pydantic, and it doesn't for me, there has to be something I'm missing.

I've set up VS Code as per https://pydantic-docs.helpmanual.io/visual_studio_code/ and it still seems to not work.


Solution

  • Fields that accept None as value can be declared using typing.Optional:

    from pydantic import BaseModel
    from typing import Optional
    
    class Foo(BaseModel):
        count: int
        size: Optional[float] = None
    

    See Field Types in the pydantic documentation for more information about the supported field types:

    typing.Optional

    Optional[x] is simply short hand for Union[x, None]; see Unions below for more detail on parsing and validation and Required Fields for details about required fields that can receive None as a value.