-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Field(default=None) overrides a field's type annotation as Optional #1761
Comments
Hello @lsorber |
Understood @PrettyWood. Could you clarify why this is the expected behaviour in v1.6.1 though? To me at least this behaviour is not expected based on the documentation. I suspect that this is the expected behaviour because "that's the way it's currently implemented". If that's the case I'm fine with that, but the reason I ask is that I'd like to understand if I misunderstood Pydantic's rule set. |
Exactly! There is even a test to make sure the implemented behaviour here works. This is why I don't call it a bug. We can discuss the why and the possible improvements that could be made but for this @samuelcolvin will probably be better suited to answer ;) |
Output of
python -c "import pydantic.utils; print(pydantic.utils.version_info())"
:Pydantic internally changes a field's type annotation from
X
toOptional[X]
when applyingField(default=None)
.Arguably, this is a bug because it is no longer possible to choose between (the semantically different)
foo: int = Field(default=None)
andfoo: Optional[int] = Field(default=None)
. To me, the former reads as "foo is a non-required (default=None) field that can take on non-null int values (int)", while the latter reads as "foo is a non-required (default=None) field that can take on nullable int values (Optional[int])".Consider the following example:
One workaround is to use a different sentinel value (see below). Is there a better way to specify "non-required non-nullable fields of a given type"?
The text was updated successfully, but these errors were encountered: