Skip to content

Type inference does not work for inherited Literal properties #6824

Closed
@antonagestam

Description

@antonagestam

I expected mypy to be able to infer that the literal in the subtype is a subtype of the property in its ancestor. Should this be allowed? I didn't find anything in the PEP defining the behavior here, but it seems like a really useful thing to be able to do.

from typing_extensions import Literal
from typing import Union


HTTPMethodName = Union[
    Literal['GET'],
    Literal['POST'],
]


class A:
    method: HTTPMethodName


class B(A):
    # works if the subclass also annotates the property
    method: HTTPMethodName = 'POST' 


class C(A):
    # error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "Union[Literal['GET'], Literal['POST']]")
    method = 'POST'

setup.cfg:

[mypy]
ignore_missing_imports = True
strict_optional = True
no_implicit_optional = True
check_untyped_defs = True
disallow_incomplete_defs = True
$ mypy --version
mypy 0.710+dev.b53dae73eebf72e3fe1f868dfa9ad008204c5701

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions