Skip to content
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

Casting away Optional #752

Closed
MatthiasThul opened this issue Dec 7, 2020 · 1 comment
Closed

Casting away Optional #752

MatthiasThul opened this issue Dec 7, 2020 · 1 comment
Assignees
Labels

Comments

@MatthiasThul
Copy link

(See python/typing#645 for a related discussion.)

Consider the following file test.py:

from typing import TypeVar, Optional

T = TypeVar('T')

def cast_away_optional(x: Optional[T]) -> T:
    assert x is not None
    return x

def foo(i: int) -> Optional[int]:
    if i == 42:
        return i
    return None

x = foo(1)
reveal_type(x)

y = cast_away_optional(x)
reveal_type(y)

assert x is not None
reveal_type(x)

PyType 2020.12.2 gives:

File "/Users/someone/code/pytype/test.py", line 15, in <module>: Optional[int] [reveal-type]
File "/Users/someone/code/pytype/test.py", line 18, in <module>: Optional[int] [reveal-type]
File "/Users/someone/code/pytype/test.py", line 21, in <module>: int [reveal-type]

It is surprising to me that y is not inferred as int while x at the end is.

Mypy 0.790 gives as expected:

test.py:15: note: Revealed type is 'Union[builtins.int, None]'
test.py:18: note: Revealed type is 'builtins.int*'
test.py:21: note: Revealed type is 'builtins.int'
@rchen152 rchen152 self-assigned this Dec 13, 2020
@rchen152 rchen152 added the bug label Dec 13, 2020
@rchen152
Copy link
Contributor

Seems to be a bug in our union matching (

elif isinstance(other_type, abstract.Union):
). In matching against Optional[T], once a value matches None, we should return a successful match, rather than going on and matching the value to T as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants