Initialization order of fields overridden in subclasses

Open
#707 9 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
tooling

Research direction

Start by reproducing the provided attrs example and reading the subclassing discussion in related issue #637, alongside the referenced dataclasses inheritance behavior in PEP 557. The issue does not name implementation files or tests; completion would require maintainer agreement on the intended initialization semantics and a verified resolution for the failing BetterXContainer case.

Written by the indexing model from the issue text.

Description

Typing

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".

Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-attrs/attrs

All issues in python-attrs/attrs

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.