Open nsoranzo opened 2 months ago
Related: #4019, #10736
Tracking conditionally defined attributes is hard, both for mypy and for humans. Generally it's preferable to have attributes always be defined, and if necessary give them a default value / optional type that can be guarded against. Though that wouldn't have helped in the linked issue, since the attribute wasn't supposed to be conditionally defined to begin with.
This sort of error can be easier to catch if you use a pattern like
if x:
foo = 1
elif y:
foo = 2
self.foo = foo
or
self.foo = _resolve_foo(x, y)
@brianschubert Thanks for the quick reply and the links. Agreed that it's hard, that's why we need a tool like mypy to help :)
As you can guess, in a project with hundreds of contributors it is nearly impossible to ensure the use of such patterns every time an instance attribute is initialised.
It's OK if there's no plan to address this, I think it's worth to have an issue specifically related to the the possibly-undefined
error code.
Bug Report
When enabling the possibly-undefined error code, a potentially undefined instance attribute doesn't trigger the error, while a potentially unbound variable does.
To Reproduce
Also available as mypy Playground, but cannot enable
enable_error_code = possibly-undefined
there.Expected Behavior
A
possible-undefined
error should be reported for line 11 as well, e.g.:Actual Behavior
No error reported for line 11.
Your Environment
--enable-error-code=possibly-undefined
mypy.ini
(and other config files): None