"default" decorator doesn't work as the keyword in attrib() did
Hi, I was using the default when setting up an attribute, but things got weird when I called something like:
a:
from attr import attrs, attrib
from random import randint
@attrs()
class Test:
num = attrib(init=False)
@num.default
def num_default(self):
return randint(0, 100000)
if __name__ == '__main__':
for i in range(10):
print(Test().num)
and b:
from attr import attrs, attrib
from random import randint
@attrs()
class Test:
num = attrib(init=False, default=randint(0, 100000))
if __name__ == '__main__':
for i in range(10):
print(Test().num)
a can work like what I want but b only return all the same value. Aren't they supposed to work like the same?
Anyway, I am also wondering if there is a way to use the factory keyword in attrib() with arguments?
They are not supposed to work the same. In the first case the default method is called on each instantiation, in the second one you set a default value when creating the class.
Your example a is the equivalent of writing:
from functools import partial
@attrs
class Test:
num = attrib(init=False, factory=partial(randint, 0, 100000))
Which also should answer your question re the factory keyword. :) Another option is using lambda.
Nice solution, thx. @hynek