Skip to content

Initialization order of fields overridden in subclasses #707

Open
@badicsalex

Description

@badicsalex

I have a code similar to the following, that relies very heavily on mypy for correctness:

import attr

class X:
    """ Some other class from the code """

class XButBetter(X):
    """ Some other class from the code """

@attr.s(auto_attribs=True)
class XContainer:
    the_x: X
    x_metadata: int = attr.ib(init=False)
    @x_metadata.default
    def _x_metadata_default(self) -> int:
        return self.the_x.get_metadata()

    def some_useful_function(self) -> str:
        """ A useful but very complex function dealing with self.the_x """

@attr.s(auto_attribs=True)
class BetterXContainer(XContainer):
    the_x: XButBetter
    def some_function(self) -> None:
        """ some code assuming the_x is the better version """

xc = XContainer(X())
xcb = BetterXContainer(XButBetter())

The last line fails with AttributeError: 'BetterXContainer' object has no attribute 'the_x', because the initialization order of the attributes changed in the subclass. Another similar issue is described on stackoverflow.

Any plans on implementing subclassing similarly to dataclasses? Would that be a breaking API change? (Probably.)

Related attrs issue I found: #637

PS.: I realize this is subclassing issue n+1 when subclassing is frowned upon, and this is somewhat similar to the classic OOP problem of subclassing Circle from Ellipse, so feel free to just say "damn man, this is not proper OOP, so wontfix".

Metadata

Metadata

Assignees

No one assigned

    Labels

    TypingTyping/stub/Mypy/PyRight related bugs.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions