Open davekch opened 2 years ago
Mypy doesn't do cross-function type narrowing. This would be difficult to implement and would likely require a new type system feature.
I understand.
Is there a workaround other than self.bar: str = None # type: ignore
, eg a flag/comment to ignore only this specific error only on methods that are decorated this way?
If you want your code to work well with static type checking, I would recommend against using this technique. Static type checkers like mypy provide a way to detect and prevent bugs in your code at type checking time, but you need to work with the type checker, not against it. This pattern is working against it.
Bug Report
When decorating a function in a way that should resolve mypy errors, mypy still reports an error.
To Reproduce
This works just fine:
A pattern I often use in this case is to move the check
if not self.bar: ...
into a decorator:which is essentially the same thing, but here mypy complains:
error: Item "None" of "Optional[str]" has no attribute "split"
Expected Behavior
mypy understands that the decorator makes sure that
self.bar
is notNone
. I also tried to make the type hints of the decorator more specific but it did not change the observed behaviour.Actual Behavior
mypy gives the same error as if the decorator were not there.
Your Environment
mypy.ini
(and other config files): none