Is there are good DRY fix for this painful design pattern?
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Tue Feb 27 03:47:43 EST 2018
On 26.02.2018 15:41, Steven D'Aprano wrote:
> I have a class with a large number of parameters (about ten) assigned in
> `__init__`. The class then has a number of methods which accept
> *optional* arguments with the same names as the constructor/initialiser
> parameters. If those arguments are None, the defaults are taken from the
> instance attributes.
>
Others have pointed out good solutions already, in particular, combining
inspect and decorators or encapsulating the parameters in an object.
Alternatively, you could reconsider your class design. Although I can't
tell from your example whether this idea would be acceptable for your
use case, consider removing your parameters from the class methods
(except from __init__) altogether so the values passed during
instantiation cannot be changed later. In exchange, add module-level
functions corresponding to each of your class methods that accept
**kwargs and that generate new instances of your class passing **kwargs
on to __init__, then call the corresponding instance method.
The stdlib textwrap module, for example, uses this approach.
Best,
Wolfgang
More information about the Python-list
mailing list