attrs icon indicating copy to clipboard operation
attrs copied to clipboard

"default" decorator doesn't work as the keyword in attrib() did

Open HoweChen opened this issue 7 years ago • 2 comments

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?

HoweChen avatar Sep 01 '19 08:09 HoweChen

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.

hynek avatar Sep 01 '19 10:09 hynek

Nice solution, thx. @hynek

HoweChen avatar Sep 02 '19 06:09 HoweChen