New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AttributeError
when accessing an attribute with a default value set in a child class
#1240
Comments
I can't quite follow everything that's happening because you're essentially breaking attrs with you |
Hi @hynek and thanks for your answer. So a class decorated by attrs is not meant to call In the docs you mentioned that it's Which is what I did. @define(slots=False, auto_attribs=True, auto_detect=True)
class B(A):
field_3: int = 0
def __attrs_pre_init__(self, field_1: int, *args, **kwargs):
super().__init__(field_1)
def __attrs_post_init__(self):
# super().__attrs_post_init__()
# raises AttributeError when accessing field_3
print(f"B.__attrs_post_init__: field_3 default = {self.field_3}")
print(self.field_3) The How attrs is expected to behave with inheritance ? Thanks ! |
You don't have to. The
It says:
I guess I can add a clarification that that's never necessary with attrs classes.
This works as expected: from abc import ABC
from attrs import define, field
@define
class A(ABC):
field_1: int = 42
field_2: int = field(init=False)
def __attrs_post_init__(self):
print(f"A.__attrs_post_init__: field_1 default = {self.field_1}")
self.field_2 = self.field_1 * 2
@define
class B(A):
field_3: int = 0
def __attrs_post_init__(self):
super().__attrs_post_init__()
print(f"B.__attrs_post_init__: field_3 default = {self.field_3}")
print(self.field_2)
print(self.field_3)
if __name__ == '__main__':
instance = B()
attrs does work with inheritance in general, but it can get a bit hairy when you use a lot of pre-inits and post-inits. JFTR, you can always inspect the >>> import inspect
>>> print(inspect.getsource(B.__init__))
def __init__(self, field_1=attr_dict['field_1'].default, field_3=attr_dict['field_3'].default):
self.field_1 = field_1
self.field_3 = field_3
self.__attrs_post_init__() |
warning added in ec9ef8d |
Hi,
I'm surprised that this
attrs
code doesn't work:When I try to access
field_3
in the child's__attrs_post_init__
, the attribute, despite having a default value like another one in the parent class, is undefined.My assumption was that, by the time
attrs
has reached__attrs_post_init__
, the fields with default values should have been set already (which is the case for the parent class)Is there some subtlety that i'm missing here with attrs initialization ?
Thanks !
The text was updated successfully, but these errors were encountered: