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

Missing error when an attribute is a variant generic #13185

Open
parched opened this issue Jul 19, 2022 · 4 comments
Open

Missing error when an attribute is a variant generic #13185

parched opened this issue Jul 19, 2022 · 4 comments
Labels
bug mypy got something wrong

Comments

@parched
Copy link

parched commented Jul 19, 2022

The following produces no errors but I expected it to be treated the same as if B.a was a get/set property (which causes a variance error)

class A:
    pass

class A2(A):
    something: str = "hello"
    
T_co = TypeVar('T_co', covariant=True)

class B(Generic[T_co]):
    def __init__(self, a: T_co) -> None:
        self.a: T_co = a  # EXPECTED: typing error here like "public attributes must have invariant type"
        
def set_a(b: B[A]) -> None:
    b.a = A()
    

b2: B[A2] = B(A2())

set_a(b2)

print(b2.a.something) # ACTUAL: runtime error here

Python 3.10, mypy 0.961 with --strict

@parched parched added the bug mypy got something wrong label Jul 19, 2022
@erictraut
Copy link

The problem here is that you have defined T_co as covariant, but given how you are using it in B, it should be declared as invariant.

@parched
Copy link
Author

parched commented Jul 19, 2022

Yes, but shouldn't mypy tell me that? It does if I explicitly create a setter for a.

@parched
Copy link
Author

parched commented Jul 19, 2022

Or is variance something that the user needs to check is correct and it's use should be flagged like Any as potentially "unsafe"?

@erictraut
Copy link

Mypy validates the variance for protocol classes but not for other standard (nominal) classes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants