1

I always want to shorten my code, for those classes have lots of variables, writing init method is time consuming.

There are few solutions for it to automatically initialize instance variables. Automatically initialize instance variables?

Since Python 3.7+, there is one more solution is to use dataclass, but since Python have shared variables during instances How to avoid having class data shared among instances?

So using dataclass to do automatic attribute assignment can be considered as good practice or it's only suitable for data-classes only?

TomSawyer
  • 3,711
  • 6
  • 44
  • 79
  • Python doesn't share instance variables between instances. Regardless, `dataclass`es should be fine if you want to use them. – martineau Aug 11 '19 at 18:30
  • @martineau i found out that `dataclass` can't have list variable for avoiding mutable default argument problem – TomSawyer Aug 11 '19 at 18:45
  • @TomSawyer Sure you can; you just have to use `default_factory` instead of assigning an actual empty list. `foo: List[int] = field(default_factory=list)`. – chepner Aug 11 '19 at 19:17
  • @tom: There's something in this [`dataclass` tutorial](https://realpython.com/python-data-classes/) explaining how to handle mutable default values with a `default_factory` in the section titled **Advanced Default Values**. – martineau Aug 12 '19 at 06:25

0 Answers0