polo
polo

Reputation: 1452

in a python attrs class, how can I override generated __init__ with my own

So I like to use attr but sometimes I need to do my own thing. can I override the __init__ method with my own?

import attr
@attr.s(auto_attribs=True)
class MyClass:
     i: int
     def __init__(self, i, special=None):
          if special:
               self.i = special
          else:
               self.i = i
>>> a = MyClass(i=1,special=2)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    a = MyClass(i=1,special=2)
TypeError: __init__() got an unexpected keyword argument 'special'

Another example:

@attr.s(auto_attribs=True)
class MyOtherClass:
     i: int
     def __init__(self, i, **kwargs):
         self.i = kwargs.get('magic',i)



>>> a = MyOtherClass(i=5,magic=12)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    a = MyOtherClass(i=5,magic=12)
TypeError: __init__() got an unexpected keyword argument 'magic'

Upvotes: 5

Views: 6820

Answers (2)

hynek
hynek

Reputation: 4146

If you pass @attr.s(auto_attribs=True, init=False), a attrs won't create an __init__ method (works the same for repr, eq, ...).


As of attrs 20.1.0, if you pass @attr.s(auto_attribs=True, auto_detect=True) or use the NG API @attr.define (no args necessary), it will automatically detect the presence of a custom __init__ (and every other __ method) on the current class and won’t overwrite it.

Upvotes: 8

ababak
ababak

Reputation: 1803

The "attrs by Examples" page says:

Sometimes, you want to have your class’s __init__ method do more than just the initialization, validation, etc. that gets done for you automatically when using @attr.s. To do this, just define a __attrs_post_init__ method in your class. It will get called at the end of the generated __init__ method.

>>> @attr.s
... class C(object):
...     x = attr.ib()
...     y = attr.ib()
...     z = attr.ib(init=False)
...
...     def __attrs_post_init__(self):
...         self.z = self.x + self.y
>>> obj = C(x=1, y=2)
>>> obj
C(x=1, y=2, z=3)

Upvotes: 4

Related Questions