Reputation: 6627
While using python-attrs, what is the good way to trigger the converter while set the attribute.
EX:
@attr.s
class A(object):
b = attr.ib(converter=str)
>>> A(b=1)
A(b='1')
>>> a = A(b=1)
>>> a.b
'1'
>>> a.b = 2
>>> a.b
2 # converter not used
Upvotes: 1
Views: 2261
Reputation: 2255
In your case, you cannot do that using attrs, by the reference of philosophy: attrs runtime impact is very close to zero because all the work is done when the class is defined. Once you’ve initialized it, attrs is out of the picture completely.
To see what the attrs real does:
import attr
import inspect
@attr.s
class A(object):
b = attr.ib(converter=str)
print(inspect.getsource(A.__init__))
the output is
def __init__(self, b):
self.b = __attr_converter_b(b)
So you can see all the magic is only done in the init function, so after the instance is initialized, attrs cannot handle it anymore, if you really want to control your own set behavior, why not using the descriptor, which is designed for class attributes.
Upvotes: 3