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

Narrowed field types are rejected #1019

Open
nickdrozd opened this issue Sep 12, 2023 · 4 comments
Open

Narrowed field types are rejected #1019

nickdrozd opened this issue Sep 12, 2023 · 4 comments

Comments

@nickdrozd
Copy link

A.x has a union type. B and C inherit from A, and B.x and C.x each have non-union types belong to the union.

class A:
    x: int | str

class B(A):
    x: int

class C(A):
    x: str

mypy --strict accepts this, but mypyc raises errors:

asdf.py:5: error: Type of "x" is incompatible with definition in class "A"
asdf.py:8: error: Type of "x" is incompatible with definition in class "A"

It would be cool if Mypyc would accept this. Barring that, the error message could be better. Something to the effect of "the types are compatible, but Mypyc requires that they be identical".

@JelleZijlstra
Copy link
Collaborator

This is correct as this code is technically unsafe (if you have an object of type A, you can do either b.x = 1 or b.x = "1", but if it's actually an instance of B or C, then one of these calls will fail). Mypy generally allows this unsoundness for practical reasons, but mypyc has to be stricter.

However, the error can likely be improved.

@nickdrozd
Copy link
Author

Is there a better way to express this logic? In my circumstance, every instance of A will be an instance of B or C; IOW, there are no unspecialized instances of A. Methods defined on the subclasses will usually be defined on A as well, and called as a backup if certain conditions are not met. There is no mutation anywhere.

@JelleZijlstra
Copy link
Collaborator

Probably mark it as read-only on the base class by using @property. Read-only attributes are covariant, read-write attributes are invariant.

@nickdrozd
Copy link
Author

That suggestion works. Feel free to close the issue, or keep it open for the error message improvement.

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

No branches or pull requests

2 participants