Skip to content

Passing arguments to __attrs_init_subclass__ #1335

Open
@tartopohm

Description

@tartopohm

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions