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

Properties, setter, and Incompatible types in assignment #4167

Closed
engnadeau opened this issue Oct 26, 2017 · 3 comments
Closed

Properties, setter, and Incompatible types in assignment #4167

engnadeau opened this issue Oct 26, 2017 · 3 comments

Comments

@engnadeau
Copy link

Expected Behaviour

  • Ability to use property setter with Union[]
  • The intention is to overload the setter

Actual Behaviour & Repro Case

Python Code

from typing import Union


class A:
    def __init__(self) -> None:
        self._foo = 0

    @property
    def foo(self) -> int:
        return self._foo

    @foo.setter
    def foo(self, value: Union[int, float]) -> None:
        self._foo = int(value)


if __name__ == '__main__':
    a = A()
    print(a.foo)

    a.foo = 123
    print(a.foo)

    a.foo = 456.789 # error thrown here
    print(a.foo)

Stdout

0
123
456

(i.e., valid Python code)

Mypy CLI

mypy --strict

Result

error: Incompatible types in assignment (expression has type "float", variable has type "int")

Notes

  • Mypy seems to be type checking the assignment using the type declared in def foo(self) -> int: instead of the declared types in the setter: def foo(self, value: Union[int, float]) -> None:

Current Solution

  • Silence the error with # type: ignore
@gvanrossum
Copy link
Member

Your hunch is correct: for properties, mypy uses the type declared in the initial @property definition as the final type for the attribute, regardless of what the @property.setter does.

I suppose we could fix this though it might require a bunch of one-off changes in odd corners of the code since properties are unique in this respect.

@srittau
Copy link
Contributor

srittau commented Feb 23, 2018

This seems similar to issue #3004, which has more discussion.

@gvanrossum
Copy link
Member

Oh, yeah, it's a duplicate.

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

No branches or pull requests

3 participants