我如何使用@property setter并使mypy开心?

问题描述 投票:1回答:1

我有以下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)

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

python-3.x python-decorators mypy
1个回答
0
投票
该问题可能与Property setter not accepted if not next to getter有关。

以下代码错误地引发错误:

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已关闭该问题并将其标记为假阳性。看来他们目前无意对其进行修复。

我们没有立即解决此问题的计划,但我们很乐意接受公关-JukkaL

考虑它的功能:)

© www.soinside.com 2019 - 2024. All rights reserved.