Open
Labels
false-positivemypy gave an error on correct codefeaturepriority-1-normaltopic-type-narrowingConditional type narrowing / binder
Description
Here's a very simple example:
from typing import *
a = ['x', None] # type: List[Optional[str]]
for i in range(len(a)):
if a[i]:
print(i, '<' + a[i] + '>')
We get an error on the last line:
__tmp__.py:5: error: Unsupported operand types for + ("str" and "Optional[str]")
Of course I can refactor this by using
for i in range(len(a)):
ai = a[i]
if ai:
print(i, '<' + ai + '>')
but that's just busy-work and doesn't necessarily make the code more readable.
(I found this in some mypy test code where the actual expression was p[i].arg so this probably needs to become fairly powerful.)
Metadata
Metadata
Assignees
Labels
false-positivemypy gave an error on correct codefeaturepriority-1-normaltopic-type-narrowingConditional type narrowing / binder
Activity
Fix strict none errors in the test subpackage.
ddfisher commentedon Sep 30, 2016
Yeah, this looks like a general binder feature to me.
[-]None checking (binder?) should reason about complex expressions[/-][+]Binder should reason about complex expressions[/+]ddfisher commentedon Sep 30, 2016
Actually, these things are pretty difficult to do correctly/safely, because you have to worry about e.g.:
gvanrossum commentedon Sep 30, 2016
I agree it's complicated (and it would be even more complicated if we considered other threads). I'm just pointing out that if we have a lot of code like this (and I've seen a lot of it in Dropbox repos) is all needs to be refactored just to shut up
--strict-optional, and that's tedious.Add mypy.ini. Fix strict none errors in the test subpackage. (#2200)
JukkaL commentedon Oct 4, 2016
The binder already isn't safe, so this wouldn't fundamentally change anything. The binder currently seems to handle
a[0]but nota[i]. Adding support for the latter hopefully wouldn't be hard. [These only seem to work withisinstancetests. A test such asif a[0]:doesn't seem to be supported, but I assume that it wouldn't be hard to fix.]Example of unsafety:
gvanrossum commentedon Oct 4, 2016
JukkaL commentedon Oct 4, 2016
I have no idea. We could perhaps generate a sample of such things from a large corpus and manually analyze them. I doubt we can reason this from first principles.
ilevkivskyi commentedon May 2, 2017
There is a lot of code like this in mypy itself:
if x[i] is not None: ...,if x.attr is not None: ..., andNone not in x(for collections). I think it makes sense to raise priority to normal here.