pytype icon indicating copy to clipboard operation
pytype copied to clipboard

`or` doesn't figure out that an `optional` on left hand side evaluates to right hand side

Open kiilerix opened this issue 5 years ago • 3 comments

I would expect Optional[str] or str to have type str. It seems like or is handled correctly in many such situations, but not in this distilled (and thus slightly pointless) minimized repro case:

d = {'x': 'y'}
[(i or d.get('b') or i).strip() for i in ['x', 'y']]

$ pytype a.py 
...
File "a.py", line 2, in <module>: No attribute 'strip' on None [attribute-error]
  In Optional[str]
...
$ pytype --version
2020.08.10

kiilerix avatar Aug 23 '20 22:08 kiilerix

simpler repro:

a = [(i or None) for i in ['x', 'y']]
reveal_type(a) # => List[Optional[str]]

martindemello avatar Aug 25 '20 23:08 martindemello

@martindemello nice! But FWIW: I'm not entirely sure if it is the same problem. It is also a bit like an opposite problem, and it might be a different code path. Your example rely on knowing that the xy list not only is "str - not None" but also "str - not None and not empty". My example only rely on knowing that the xy list "str - not None but potentially empty" and that the computed list thus also is "str - not None but potentially empty" .

kiilerix avatar Aug 25 '20 23:08 kiilerix

@kiilerix for i in ['x', 'y'] should make i strictly a str, not an Optional[str], and so i or ... should always be i

martindemello avatar Aug 26 '20 00:08 martindemello