Is there are good DRY fix for this painful design pattern?
Antoon Pardon
antoon.pardon at vub.be
Mon Feb 26 10:19:43 EST 2018
On 26-02-18 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.
>
This is what I came up with at short notice:
def passthrough(func):
def wrapper(self, **kwds):
for argn in "bashful doc dopey grumpy happy sleepy sneezy".split():
if argn not in kwds:
kwds[argn] = getattr(self, argn)
func(self, **kwds)
return wrapper
class Foo:
def __init__(self, bashful, doc, dopey, grumpy,
happy, sleepy, sneezy):
self.bashful = bashful
self.doc = doc
self.dopey = dopey
self.grumpy = grumpy
self.happy = happy
self.sleepy = sleepy
self.sneezy = sneezy
@passthrough
def spam(self, bashful=None, doc=None, dopey=None,
grumpy=None, happy=None, sleepy=None,
sneezy=None):
print(bashful, doc, dopey, grumpy, happy, sleepy, sneezy)
foo = Foo('a', 'b', 'c', 'd', 'e', 'f', 'g')
foo.spam(happy = 1) # prints => a b c d 1 f g
More information about the Python-list
mailing list