如何使用attr.validators.optional

时间:2019-02-07 09:29:00

标签: python python-2.7 python-attrs

根据attrs documentation,可选属性应声明如下:

>>> @attr.s
... class C(object):
...     x = attr.ib(validator=attr.validators.optional(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, validator=<instance_of validator for type <type 'int'>>, type=None, kw_only=False), <type 'int'>, '42')
>>> C(None)
C(x=None)

但是,当我尝试使用可选属性时,会得到以下结果:


python
Python 2.7.15 (default, Jul 23 2018, 21:27:06)
[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.2)] on darwin

具有强制属性的类

类定义

>>> import attr
>>> @attr.s
... class Result(object):
...   log = attr.ib(validator=attr.validators.instance_of(str))
...

课程实例

缺少属性
>>> test = Result()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 2 arguments (1 given)

类型无效
>>> test = Result(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<attrs generated init 086c7a4a2a56d2e9002255c4e881a832c6bc5360>", line 4, in __init__
  File "/.../.venv/lib/python2.7/site-packages/attr/validators.py", line 32, in __call__
    value,
TypeError: ("'log' must be <type 'str'> (got 1 that is a <type 'int'>).", Attribute(name='log', default=NOTHING, validator=<instance_of validator for type <type 'str'>>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), <type 'str'>, 1)

正确的类型
>>> test = Result('aaa')
>>> test.log
'aaa'

具有可选属性的类

类定义

>>> import attr
>>> @attr.s
... class Result(object):
...   log = attr.ib(validator=attr.validators.optional(attr.validators.instance_of(str)))
...

课程实例

缺少属性
>>> test = Result()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 2 arguments (1 given)

KO

类型无效
>>> test = Result(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<attrs generated init 7e2ff957cec78e81193f38c89e2f4eb2ff2dad4e>", line 4, in __init__
  File "/.../.venv/lib/python2.7/site-packages/attr/validators.py", line 106, in __call__
    self.validator(inst, attr, value)
  File "/.../.venv/lib/python2.7/site-packages/attr/validators.py", line 32, in __call__
    value,
TypeError: ("'log' must be <type 'str'> (got 1 that is a <type 'int'>).", Attribute(name='log', default=NOTHING, validator=<optional validator for <instance_of validator for type <type 'str'>> or None>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), <type 'str'>, 1)

正确的类型
>>> test = Result('aaa')
>>> test.log
'aaa'


使用可选属性在做什么? 我的误解在哪里?

1 个答案:

答案 0 :(得分:0)

正确的类定义是:

>>> @attr.s
... class Result(object):
...   log = attr.ib(default=None, validator=attr.validators.optional(attr.validators.instance_of(str)))