Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent narrowing of Union and TypeVar with constraints and neglect of @final #10898

Open
tyralla opened this issue Jul 31, 2021 · 0 comments
Labels
bug mypy got something wrong topic-final PEP 591 topic-type-narrowing Conditional type narrowing / binder

Comments

@tyralla
Copy link
Collaborator

tyralla commented Jul 31, 2021

I had a short discussion about this with @JelleZijlstra on Gitter.

When narrowing the constrained type variable, Mypy seems to ignore the final decorator. When removing the final decorator, Mypy's output changes neither for the non-generic function f nor the generic function g. Shouldn't Mypy consistently report an error or not in both cases (regardless of marking the classes as final or not)? If I understand correctly, Mypy allows changing the signature of __init__ when subclassing. So the reports are correct for f when using final and correct for g when not using final, aren't they?

from typing import final, Type, TypeVar, Union

@final
class A:
    def __init__(self, a: int) -> None:
        ...

@final
class B:
    def __init__(self, b: str) -> None:
        ...

U = Union[A, B]
T = TypeVar("T", A, B)

def f(x: Type[U]) -> U:
    if issubclass(x, A):
        reveal_type(x)
        # Revealed type is "A"
        return x(a=1)
    return x(b="a")

def g(x: Type[T]) -> T:
    if issubclass(x, A):
        reveal_type(x)
        # Revealed type is "A*"
        # Revealed type is "<subclass of "B" and "A">"
        return x(a=1)
        # Unexpected keyword argument "a" for <subclass of "B" and "A">
    return x(b="b")
@tyralla tyralla added the bug mypy got something wrong label Jul 31, 2021
@JelleZijlstra JelleZijlstra added topic-type-narrowing Conditional type narrowing / binder topic-final PEP 591 labels Mar 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-final PEP 591 topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

No branches or pull requests

2 participants