pyright icon indicating copy to clipboard operation
pyright copied to clipboard

assignment to explicit annotated variable does not remove Union's Any-ability

Open pinterior opened this issue 3 years ago • 4 comments

Describe the bug

when value of Union[someT, Any] is assigned to x: someT, x has type Union[someT, Any] not someT.

To Reproduce

from typing import Any, Union
from typing_extensions import reveal_type

def t0() -> Any: ...
def t1() -> str: ...
def t2() -> Union[str, Any]: ...
def t3() -> Union[str, int, Any]: ...

r0 = t0()
r1 = t1()
r2 = t2()
r3 = t3()

reveal_type(r0)
v0: str = r0
reveal_type(v0)

reveal_type(r1)
v1: str = r1
reveal_type(v1)

reveal_type(r2)
v2: str = r2
reveal_type(v2)  # str expected, but str|Any

reveal_type(r3)
v3: Union[str, int] = r3
reveal_type(v3)  # str|int expected, but str|int|Any
  cc.py:14:13 - information: Type of "r0" is "Any"
  cc.py:16:13 - information: Type of "v0" is "str"
  cc.py:18:13 - information: Type of "r1" is "str"
  cc.py:20:13 - information: Type of "v1" is "str"
  cc.py:22:13 - information: Type of "r2" is "str | Any"
  cc.py:24:13 - information: Type of "v2" is "str | Any"
  cc.py:26:13 - information: Type of "r3" is "str | int | Any"
  cc.py:28:13 - information: Type of "v3" is "str | int | Any"

Expected behavior

v2 and v3 do not have possibility to be Any as well as v0.

VS Code extension or command-line

command-line tool 1.1.290

pinterior avatar Jan 24 '23 19:01 pinterior

The current behavior is as designed. The type narrowing rules for Any are a bit different from any other types in the Python type system.

Is there a specific problem you see with the current behavior, in terms of type safety or functionality? Or is it just working differently than you expected?

erictraut avatar Jan 24 '23 19:01 erictraut

the problem affects on match exhaustiveness.

for example:

from typing import Any, Union, Literal

# stub for legacy code not annotated and inferred as `Union[str, Literal[3], Any]`
# but known not to be other than `3` or `str`.
def some_legacy_code() -> Union[str, Literal[3], Any]: ...

def f() -> int:
    v: Union[str, Literal[3]] = some_legacy_code()
    match v:
        case 3:
            return 0
        case str():
            return 1
  ma.py:7:12 - error: Function with declared type of "int" must return value on all code paths
    Type "None" cannot be assigned to type "int" (reportGeneralTypeIssues)

pinterior avatar Jan 25 '23 04:01 pinterior

If you have an Any type, exhaustiveness cannot be guaranteed, so this behavior is correct.

erictraut avatar Jan 25 '23 06:01 erictraut

I thought semantic of Union assignment is flatMap each element by assign to lhs type semantic recursively and construct new Union type, so Any in rhs Union will be erased. but the guess was wrong. thank you.

pinterior avatar Jan 25 '23 15:01 pinterior