attr.ib 忽略值参数

attr.ib ignores value parameter

attr.ib 接受一个 repr 参数,可以是 bool 或 callable。

To override how the attribute value is formatted, pass a callable that takes a single value and returns a string. Note that the resulting string is used as-is, i.e. it will be used directly instead of calling repr() (the default).

传递时似乎并非如此 datetime.datetime.fromisoformat():

import datetime
import attr

@attr.s
class Test(object):
    foo: str = attr.ib()
    dt: datetime.datetime = attr.ib(repr=datetime.datetime.isoformat)

结果:

>>> t = Test(foo='bar', dt=datetime.datetime.utcnow())                                                                                                                                                                                                       
>>> t                                                                                                                                                                                                                                                        
Test(foo='bar', dt=datetime.datetime(2019, 10, 31, 17, 59, 34, 603971))

预计:

Test(foo='bar', dt='2019-10-31T17:59:34.603971')

事实上,似乎任何参数都被忽略了。这是对 attr 文档中示例的轻微修改:

>>> @attr.s 
... class C(object): 
...     user = attr.ib() 
...     password = attr.ib(repr=lambda value: value[:2]) 
...                                                                                                                                                                                                                                                          
>>> C("me", "s3kr3t")                                                                                                                                                                                                                                        
C(user='me', password='s3kr3t')

我在这里错过了什么?

您的 attrs 安装一定是太旧了。您的代码与 attrs 19.3:

完美配合
>>> import datetime
>>> import attr
>>>
>>> @attr.s
... class Test(object):
...     foo: str = attr.ib()
...     dt: datetime.datetime = attr.ib(repr=datetime.datetime.isoformat)
...
>>> Test(foo='bar', dt=datetime.datetime.utcnow())
Test(foo='bar', dt=2019-11-01T05:40:59.745157)

您可以使用以下方式查看 attrs 的版本:

>>> attr.__version__
'19.3.0'

repr 功能已在一个月前于 2019-10-01 发布的 19.2.0 中添加。