【问题标题】:stacking attrs attributes decorators堆叠 attrs 属性装饰器
【发布时间】:2020-01-12 07:27:26
【问题描述】:

我正在尝试为两个属性重用验证器功能。我知道我可以在外部创建函数并在验证器中引用它,但是像这样堆叠装饰器在技术上是否正确:

In [6]: @attr.s 
   ...: class A: 
   ...:     a = attr.ib() 
   ...:     b = attr.ib() 
   ...:      
   ...:     @a.validator 
   ...:     @b.validator 
   ...:     def a_b_check(self, attribute, value): 
   ...:         assert value == 5 
   ...:                                                                                                                 

In [7]: A(5,5)                                                                                                          
Out[7]: A(a=5, b=5)

In [8]: A(5,6)                                                                                                          
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-8-ec475f254e70> in <module>
----> 1 A(5,6)

<attrs generated init 71300c05faf88cf49c2dcea04f8137146d4dac79> in __init__(self, a, b)
      4     if _config._run_validators is True:
      5         __attr_validator_a(self, __attr_a, self.a)
----> 6         __attr_validator_b(self, __attr_b, self.b)

<ipython-input-6-701125903dd2> in a_b_check(self, attribute, value)
      7     @b.validator
      8     def a_b_check(self, attribute, value):
----> 9         assert value == 5
     10 

AssertionError: 

In [9]: A(6,5)                                                                                                          
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-9-4582d95e8377> in <module>
----> 1 A(6,5)

<attrs generated init 71300c05faf88cf49c2dcea04f8137146d4dac79> in __init__(self, a, b)
      3     self.b = b
      4     if _config._run_validators is True:
----> 5         __attr_validator_a(self, __attr_a, self.a)
      6         __attr_validator_b(self, __attr_b, self.b)

<ipython-input-6-701125903dd2> in a_b_check(self, attribute, value)
      7     @b.validator
      8     def a_b_check(self, attribute, value):
----> 9         assert value == 5
     10 

AssertionError: 

测试表明验证运行良好,但不确定是否发生了问题。

【问题讨论】:

    标签: python python-attrs


    【解决方案1】:

    我希望它能够正常工作,因为验证器 doesn't change the method at all and just memorizes it 的 @-notation。

    如果您想重复使用验证器,我建议使用更通用且也可以跨类工作的函数。

    【讨论】:

      猜你喜欢
      • 2014-12-16
      • 1970-01-01
      • 2020-12-16
      • 2019-07-29
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 2020-06-20
      • 2013-08-19
      相关资源
      最近更新 更多