Reputation: 1514
Why does Pylance warn for Alice?
I expect that field seed
should be identical for both classes User1
and User2
.
import random
from typing import Annotated
from pydantic import BaseModel, Field
RandomInt = Annotated[int, Field(default_factory=lambda:random.randint(0, 1000))]
class User1(BaseModel):
name : str
seed : RandomInt
class User2(BaseModel):
name : str
seed : int = Field(default_factory=lambda: random.randint(0, 1000))
if __name__ == '__name__':
alice = User1(name='Alice')
bob = User2(name='Bob')
But instead Pylance warns
(variable) name: str
Argument missing for parameter "seed"PylancereportGeneralTypeIssues
Even though the code runs perfectly and the default_factory
defined in RandomInt
does its job.
Upvotes: 1
Views: 1365
Reputation: 147
This is specific behavior from Pydantic which supports default_factory
, but Python's type system doesn't know that Pydantic will generate a default value. To Python's type system (and thus Pylance) RandomInt
is an annotated int
, and Pylance (as well as MyPy and others) will ignore any annotations, since they're application-specific.
Note that pydantic.Field()
is type-hinted itself as returning a value (I believe it's hinted as Any
?), which is why Pylance won't give a warning about missing default value (because a default value exists) for User2
, but warns about no default value in User1
.
Upvotes: 0
Reputation: 2958
The usage in User1.seed
and User2.seed
is not equivalent. Pydantic's Field
is not a type annotation, it must be used as a value (as is for User2.seed
). Such, pydantic just interprets User1.seed
as an int
field, with no default value, and so requires you to provide a value on creation.
Annotated
is used for providing non-type annotations alongside type annotations (type annotations are the norm, but annotations can be used for another applications).
Upvotes: 1