python-attrs / python-attrs/attrs

Passing arguments to `__attrs_init_subclass__`

Open
#1,335 4 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Hello, thanks for the great work!

My question/issue is related to __attrs_init_subclass__ that was recently added.
PEP 487 allows for passing arguments (not sure whether that's the proper name) at class definition.
The use case, for me, would be to have some sort of abstract class attributes that should be defined by concrete classes.

To make it short, reusing the example from the docs, this works

class Base:
   @classmethod
   def __init_subclass__(cls, foo):
       cls.foo = foo
       print(f"Base has been subclassed by attrs {cls} and foo={cls.foo}.")


class Derived(Base, foo=42):
   pass
>>> Base has been subclassed by attrs <class '__main__.Derived'> and foo=42.

while

import attrs


class Base:
   @classmethod
   def __attrs_init_subclass__(cls, foo):
       cls.foo = foo
       print(f"Base has been subclassed by attrs {cls} and foo={cls.foo}.")


@attrs.define
class Derived(Base, foo=12):
   pass

does not, throwing TypeError: Derived.__init_subclass__() takes no keyword arguments.

Would there be any workaround?

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.

Research direction

Start at attrs' attrs_init_subclass entry point and compare its class-definition handling with the PEP 487 init_subclass example in the issue. Reproduce the @attrs.define class Derived(Base, foo=12) case and verify whether keyword arguments reach Base.attrs_init_subclass; done means the example works without TypeError or the supported workaround is documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.