如何使用类型提示来注释仅写的属性
我想拥有一个仅写作的属性,当有人更改它时会通知我。另外,我不得不重新分配名称(此处var
),以便在班级的名称空间中没有额外的名称。这违反了Mypy规则。
这是简化的版本:
class A:
def var(self, value):
print("value changed:", value)
var = property(fset=var)
obj = A()
obj.var = 10
obj.var = "hi"
mypy错误消息:
main.py:5: error: Incompatible types in assignment (expression has type "property", variable has type "Callable[[A, Any], Any]")
main.py:9: error: Cannot assign to a method
main.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "Callable[[Any], Any]")
main.py:10: error: Cannot assign to a method
main.py:10: error: Incompatible types in assignment (expression has type "str", variable has type "Callable[[Any], Any]")
Found 5 errors in 1 file (checked 1 source file)
如何使mypy快乐而不用#type抑制错误:ignore
?
我目前的解决方法是:
class A:
def temp(self, value):
print("value changed:", value)
var = property(fset=temp)
del temp
obj = A()
obj.var = 10
obj.var = "hi"
有什么更好的方法吗?
I would like to have a write-only property that notifies me when somebody changes it. Also I had to re-assign the name(here var
) in order not to have an extra name in class's namespace. This goes against Mypy rules.
Here is the simplified version:
class A:
def var(self, value):
print("value changed:", value)
var = property(fset=var)
obj = A()
obj.var = 10
obj.var = "hi"
Mypy error messages:
main.py:5: error: Incompatible types in assignment (expression has type "property", variable has type "Callable[[A, Any], Any]")
main.py:9: error: Cannot assign to a method
main.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "Callable[[Any], Any]")
main.py:10: error: Cannot assign to a method
main.py:10: error: Incompatible types in assignment (expression has type "str", variable has type "Callable[[Any], Any]")
Found 5 errors in 1 file (checked 1 source file)
How can I make Mypy happy without suppressing the error with # type: ignore
?
My current attempt to solve it is:
class A:
def temp(self, value):
print("value changed:", value)
var = property(fset=temp)
del temp
obj = A()
obj.var = 10
obj.var = "hi"
Is there any better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎没有其他方法,Mypy不允许我在班级主体中重新定义名称。可以使用类变量,但没有方法。
尽管我可以使用问题中显示的临时方法,但我更喜欢使用
@property
使用getter和setter定义属性,然后手动升高attributeError
:Seems like there is no other way, Mypy doesn't let me re-define names in the class body. It's OK with class variables but not with methods.
Although I could use that temporary method that I showed in the question, I prefer defining a property using
@property
decorator with both getter and setter and manually raisingAttributeError
: