我怎样才能使用@属性 setter 并让 mypy 开心?

How can I use @property setters and make mypy happy?

我有以下 example.py 文件:

class Location(object):
    def __init__(self, latitude, longitude):
        self.latitude = latitude
        self.longitude = longitude

    @property
    def latitude(self):
        return self._latitude

    @property
    def longitude(self):
        return self._longitude

    @latitude.setter
    def latitude(self, latitude):
        """Setter for latiutde."""
        if not (-90 <= latitude <= 90):
            raise ValueError('latitude was {}, but has to be in [-90, 90]'
                             .format(latitude))
        self._latitude = latitude

    @longitude.setter
    def longitude(self, longitude):
        """Setter for longitude."""
        if not (-180 <= longitude <= 180):
            raise ValueError('longitude was {}, but has to be in [-180, 180]'
                             .format(longitude))
        self._longitude = longitude

    def __repr__(self):
        return 'Location({}, {})'.format(self.latitude, self.longitude)

    __str__ = __repr__


munich = Location(48.137222222222, 11.57555)
print(munich)
try:
    munich.latitude = 200
    print("This should not work")
except ValueError:
    pass

当我 运行 mypy example.py(mypy 版本 0.73)时,我得到了几个错误:

$ mypy example.py 
example.py:14: error: Name 'latitude' already defined on line 6
example.py:14: error: "Callable[[Any], Any]" has no attribute "setter"
example.py:22: error: Name 'longitude' already defined on line 10
example.py:22: error: "Callable[[Any], Any]" has no attribute "setter"
example.py:39: error: Property "latitude" defined in "Location" is read-only
Found 5 errors in 1 file (checked 1 source file)

为什么我会得到这些,我该如何解决?

这个问题可能与 Property setter not accepted if not next to getter 有关。

The following code incorrectly raises an error:

class Config(object):

    @property
    def my_proprty(self):
        return None

    def _other(self):
        pass

    @my_proprty.setter
    def my_proprty(self, val):
        pass Error:
mypytest.py: note: In class "Config": mypytest.py:12: error:
Callable[[Any], Any] has no attribute "setter"

MyPy 关闭了该问题并将其标记为误报。看来他们目前还没有修好它的打算。

We don't have immediate plans for fix this issue, but we are happy to receive a PR. - JukkaL

将 getter 和 setter 移动到彼此旁边(首先是 getter)应该可以解决问题。

将其视为一项功能:)