Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Narrowing types to Literal using in syntax #12535

@tusharsadhwani

Description

@tusharsadhwani

Take this example code:

x = "a"
reveal_type(x)
assert x in ("a", "b", "c")
reveal_type(x)

y = 20
reveal_type(y)
assert y == 10 or y == 20 or y == 50
reveal_type(y)

The current output of this is:

$ mypy x.py 
x.py:2: note: Revealed type is "builtins.str"
x.py:4: note: Revealed type is "builtins.str"
x.py:7: note: Revealed type is "builtins.int"
x.py:9: note: Revealed type is "builtins.int"

If mypy were to support type narrowing using chained or statements and in statements, the output would look like:

$ mypy x.py 
x.py:4: note: Revealed type is "builtins.str"
x.py:6: note: Revealed type is "Union[Literal['a'], Literal['b'], Literal['c']]"
x.py:9: note: Revealed type is "builtins.int"
x.py:11: note: Revealed type is "Union[Literal[10], Literal[20], Literal[50]]"

I think doing simple narrowing here would be relatively easy and very useful.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions