What is the best way to do automatic attribute assignment in Python, and is it a good idea?

Viewed 12643

Instead of writing code like this every time I define a class:

class Foo(object): 
     def __init__(self, a, b, c, d, e, f, g):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e
        self.f = f
        self.g = g

I could use this recipe for automatic attribute assignment.

class Foo(object):
     @autoassign
     def __init__(self, a, b, c, d, e, f, g):
        pass

Two questions:

  1. Are there drawbacks or pitfalls associated with this shortcut?
  2. Is there a better way to achieve similar convenience?
9 Answers

From Python 3.7+ you can use a Data Class, which achieves what you want and more.

It allows you to define fields for your class, which are attributes automatically assigned.

It would look something like that:

@dataclass
class Foo:
    a: str
    b: int
    c: str
    ...

The __init__ method will be automatically created in your class, and it will assign the arguments of instance creation to those attributes (and validate the arguments).

Note that here type hinting is required, that is why I have used int and str in the example. If you don't know the type of your field, you can use Any from the typing module.

Related