Pyright: Optional[T] of T never match `None`

Created on 6 Apr 2020  路  3Comments  路  Source: microsoft/pyright

I want to define the following unwrap function, which unwrap T from Optional[T].

from typing import Optional, TypeVar
T = TypeVar("T")
def unwrap(v: Optional[T]) -> T:
    if v is None:
        raise ValueError
    return v

However this unwrap doesn't work well with pyright, while it works well with mypy.

import random
def f() -> Optional[int]:
    return random.choice([0, None])
a: int = unwrap(f())  # Error: Type "None" cannot be assigned to type "int"

I think the cause is that pyright resolves T with Optional[int] instead of int.

I'm glad if pyright works well with this situation.

addressed in next version bug

All 3 comments

Thanks for the bug report. I'm able to repro the problem, and I'll look into it.

This will be fixed in the next published version of pyright. Thanks again for the bug report!

This is fixed in 1.1.31, which I just published.

Was this page helpful?
0 / 5 - 0 ratings