Closed
Labels
Description
Expected Behaviour
- Ability to use property
setterwithUnion[] - 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
Mypyseems to be type checking the assignment using the type declared indef foo(self) -> int:instead of the declared types in thesetter:def foo(self, value: Union[int, float]) -> None:
Current Solution
- Silence the error with
# type: ignore
Reacted by Halla Moore, Martin Thoma and jeanmonet
Activity
gvanrossum commentedon Oct 27, 2017
Your hunch is correct: for properties, mypy uses the type declared in the initial
@propertydefinition as the final type for the attribute, regardless of what the@property.setterdoes.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 commentedon Feb 23, 2018
This seems similar to issue #3004, which has more discussion.
gvanrossum commentedon Feb 23, 2018
Oh, yeah, it's a duplicate.