gpt4 book ai didi

Python 属性包 : validators after instantiation

转载 作者:行者123 更新时间:2023-12-02 17:07:40 25 4
gpt4 key购买 nike

python 的 attrs 包提供了一种在实例化时验证传递的变量的简单方法 (example taken from attrs page):

>>> @attr.s
... class C(object):
... x = attr.ib(validator=attr.validators.instance_of(int))
>>> C(42)
C(x=42)
>>> C("42")
Traceback (most recent call last):
...
TypeError: ("'x' must be <type 'int'> (got '42' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, factory=NOTHING, validator=<instance_of validator for type <type 'int'>>, type=None), <type 'int'>, '42')

正如抛出的异常所证明的那样,这很有效。但是,当我在实例化后更改 x 的值时,没有抛出异常:

c = C(30)
c.x = '30'

对于静态对象,这种行为可能没问题,但假设对象是静态的对我来说似乎非常危险。是否有一种变通方法可以使验证器具有在实例化后也可以工作的属性?

最佳答案

version 20.1.0他们添加了 on_setattr:

A callable that is run whenever the user attempts to set an attribute (either by assignment like i.x = 42 or by using setattr like setattr(i, "x", 42)). It receives the same arguments as validators: the instance, the attribute that is being modified, and the new value.

所以,添加:

import attr

@attr.s
class C(object):
x = attr.ib(
validator=attr.validators.instance_of(int),
on_setattr = attr.setters.validate, # new in 20.1.0
)

产量

C(42)
# C(x=42)
C("42")
# TypeError: ("'x' must be <class 'int'>

此外,特别是对于您示例中的字符串输入,您可能会发现 attrs 转换器很方便。例如,要自动转换:

@attr.s
class CWithConvert(object):
x = attr.ib(
converter=int,
validator=attr.validators.instance_of(int),
on_setattr = attr.setters.validate,
)

CWithConvert(42)
# CWithConvert(x=42)
CWithConvert("42")
# CWithConvert(x=42) # converted!
CWithConvert([42])
# TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

小心:

CWithConvert(0.8)
# CWithConvert(x=0) # float to int!

关于Python 属性包 : validators after instantiation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com