-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
Mypy does not infer that a dataclass field is optional when None is assigned #13934
Comments
import dataclasses as dc
from typing import Optional
@dc.dataclass
class C:
j: Optional[int] = None Actual Results
mypy version: 0.982 (compiled: yes). This is not a bug, please close it. |
My point is dataclass’s ivars are documented to be seen as optional without explicit FWIW, PyCharm recognizes it and reports no error. |
Earlier versions of PEP 484 indicated that function parameters with a default value of Mypy has a flag called While PEP 484 was talking about function parameters, I would think that dataclass fields should likewise not support implicit The Python docs that you mentioned should probably be updated accordingly so they don't lead users to assume that implicit |
Yes, what @erictraut said. PEP 484 was revised to recommend against "implicit TL;DR: the bugs are in the CPython docs and pycharm, not mypy. |
Dataclass has been a part of stdlib for a long time now. The chance this behavior will change are slim. For all intents and purposes it is a documented feature. I understand the default behavior of mypy, my request was limited in scope by instances of dataclass only. |
The behavior we're discussing here pertains to static type checking, not to the runtime behavior of dataclass. There is no need for the dataclass runtime behavior to change. It does not enforce any runtime typing. It ignores whatever expression you specify in the type annotation, so you could enter a completely nonsensical type like It's up to mypy and other static type checkers to interpret the meaning of the type annotation and report any type violations. Your code sample has a type violation because you're attempting to assign |
The practical outcome is that valid code per stdlib documentation will be flagged as erroneous. I will forward the issue with the stdlib maintainers. |
Looks like @hauntsaninja's beaten you to it. |
The stdlib documentation has now been revised, and the revisions have been backported to the 3.11 and 3.10 branches. See python/cpython#98576 for details! |
Bug Report
It's documented that a dataclass field can be declared as optional without
Optional
or| None
by simply assigningNone
as a default value.However, mypy fails to infer this.
To Reproduce
Expected Behavior
No errors
Actual Behavior
Your Environment
The text was updated successfully, but these errors were encountered: