user3414663
user3414663

Reputation: 583

How to make a Python Dataclass mixin?

To make a dataclass in Python you typically use the decorator. Something like:

from dataclasses import dataclass


@dataclass
class Foo:
    n: int = 1

    def bump(self):
        self.n += 1

Alternatively you can use make_dataclass to do something like

Foo = make_dataclass('Foo',
                   [('n', int)],
                   namespace={'bump': lambda self: self.n += 1})

Is there a way to make a mixin class, say Dataclass, so that you could write the first form as follows?

class Foo(Dataclass):
    n: int = 1

    def bump(self):
        self.n += 1

Or is there a reason why that might be undesirable?

Upvotes: 0

Views: 71

Answers (1)

couteau
couteau

Reputation: 319

It depends on what you want the mixin to do and what version of python you are on. As of python 3.11, you can declare a class decorated with @dataclass_transform, and subclasses will then be treated similarly to a dataclass by type checkers/language servers, in that they will typehint calls to the class’s constructor with any class attributes/defaults declared in the class. But dataclass_transform will not automatically generate a constructor or other magic methods the way the @dataclass decorator does. You would have to implement all the dataclass logic yourself in the base class.

Upvotes: 0

Related Questions