Alternative to __slots__

I would like to have a built-in which creates a slot:

class X:
    a = slot(doc='field a')
    b = slot(doc='field b')

It virtually adds the name to the __slots__ list. No need to pass the field name as argument, it can be set in __set_name__().

The advantage over simple __slots__ is that it can have other options and perform some magic, like control the attribute type or even change the default constructor. It could be an alternative to dataclass.

Sort of related is an idea I’ve been discussing to defer slot creation until the first instance of a class is created. Until that time, __slots__ could be changed. My primary use case is dataclass(slots=True), but it could be more widely used.

1 Like

That would have to have a way for meta classes to opt out of this. I have some classes where __slots__ has a side effect during class creation and the behaviour you propose would break this.