Skip to content
Advertisement

Automatically-generated Python constructor

I have countless Python classes from various projects from SQLAlchemy (and a couple from Pygame as well), and I recently noticed a pattern in many of them: their constructors always went something like this:

class Foo(Base):
    def __init__(self, first, last, email, mi=""):
        self.first = first
        self.last = last
        self.email = email
        self.mi = mi

… whereby the only thing the constructor did was to transfer a set of positional arguments into an exactly identically named set of data members, performing no calculation or other function calls whatsoever.

It seems to me that this repetition is unnecessary and prone to human error upon change.

This leads me to the question here: is it possible to automatically generate such an __init__(self, ...) function, preferably without mucking around with CPython bytecode or using templates/macros to alter the source file itself?

Advertisement

Answer

For python >= 3.7, the proper way of handling this is through dataclasses:

This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement