Search code examples
pythonpython-typingpyright

Pyright exhaustive check on literal only works for parameter, not properties


This works:

def test(it: Literal['a', 'b']) -> str:
    if it == 'a':
        return 'a'
    elif it == 'b':
        return 'b'
    # No error, exhaustive

But this doesn't:

@dataclass
class Foo:
    foo:  Literal['a', 'b']

def test(it: Foo) -> str:
    foo = it.foo
    if foo == 'a':
        return 'a'
    elif foo == 'b': # Correctly infers that foo is Literal['b'] without the check
        return 'b'

    # Error, must return str

Why?


Solution

  • It's apparent that this is a PyRight bug that it can't infer the type of foo from foo = it.foo.

    For now, you would have to explicitly type hint foo with:

    foo: Literal['a', 'b'] = it.foo
    

    Demo here