简体   繁体   English

如何使用类型提示注释只写属性

[英]How to annotate a write-only property using type hints

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.此外,我必须重新分配名称(此处为var ),以免在类的命名空间中有额外的名称。 This goes against Mypy rules.这违反了 Mypy 规则。

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: 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)

How can I make Mypy happy without suppressing the error with # type: ignore ?如何在不使用# type: ignore抑制错误的情况下让 Mypy 开心?

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?有没有更好的办法?

Seems like there is no other way, Mypy doesn't let me re-define names in the class body.似乎没有其他办法,Mypy 不允许我在类主体中重新定义名称。 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 raising AttributeError :虽然我可以使用我在问题中展示的临时方法,但我更喜欢使用带有 getter 和 setter 的@property装饰器定义属性并手动提高AttributeError

class A:
    @property
    def var(self):
        raise AttributeError("unreadable attribute 'var'")

    @var.setter
    def var(self, value):
        print("value changed:", value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM