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

Property getters and setters can't have different types #17808

Closed
dalemyers opened this issue Sep 22, 2024 · 2 comments
Closed

Property getters and setters can't have different types #17808

dalemyers opened this issue Sep 22, 2024 · 2 comments
Labels
bug mypy got something wrong

Comments

@dalemyers
Copy link

Bug Report

If you use the @property decorator and give your getter and setter different types, then mypy complains about it.
To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=3e608374fa0ce9363a3c22d015642d4b

class Foo:
    
    _myprop: int
    
    def __init__(self, myprop: str | int) -> None:
        self.myprop = myprop
        
    @property
    def myprop(self) -> int:
        return self._myprop
        
    @myprop.setter
    def myprop(self, value: str | int) -> None:
        assert isinstance(value, str) or isinstance(value, int)
        self._myprop = int(myprop)

Expected Behavior

Setters should be able to accept a broader range of types than the getter as coercion or other conversions may take place.

Actual Behavior

It is not allowed:

main.py:6: error: Incompatible types in assignment (expression has type "str | int", variable has type "int")  [assignment]
main.py:15: error: Name "myprop" is not defined  [name-defined]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

Mypy playground using version 1.11.2 and Python version 3.12. No options were set.

@dalemyers dalemyers added the bug mypy got something wrong label Sep 22, 2024
@TeamSpen210
Copy link
Contributor

See #3004, this is quite an old issue. One workaround you can do is to create a custom descriptor class, that will allow different types for get and set.

@dalemyers
Copy link
Author

Ah, thanks. There were so many issues when I searched I couldn't find the right one. This can be closed as a dupe.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Sep 22, 2024
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

3 participants