One of the cool things of Scala is that, in general, you don’t need to write a lot of boilerplate while doing things in the “normal way”.
As an example, while defining a class which constructor requires one or more arguments, there’s no need to assign the parameters to instance attributes, this is done out of the box by the compiler while creating the Java code:
Python, like many other languages, does not behave that way, therefore you must assign the attributes to instance variables. Someone would argue that this is indeed the pythonic way to work, making things as explicit as possible. Letting aside that the method __init__ is not a constructor, you can do the assigment with the following snippet of code:
It turns out that a high percentage of the time, the only thing you may need to do in your __init__ methods is assigning the parameters to instance variables. Being a common behavior, it seems to me like a nice chance to build a decorator . Here it goes:
The function that builds the decorator (autoinit) is doing simple things:
- retrieve the parameter names and the default keyword parameter values
- build a function, which is the value returned by the function autoinit, which will inspect both args and kwargs while creating a new instance object, retrieve the actual value for every parameter, and assign them to instance attributes.
An usage example: