How to reduce the DRY violation in this code

Paul Rubin no.email at nospam.invalid
Tue Sep 27 13:20:48 EDT 2016


Steve D'Aprano <steve+python at pearwood.info> writes:
> class Spam:
>     def __init__(self, bashful=10.0, doc=20.0, dopey=30.0, 
>                  grumpy=40, happy=50, sleepy=60, sneezy=70):
>         # the usual assign arguments to attributes dance...
>         self.bashful = bashful
>         self.doc = doc
>         # etc.

     def __init__(self, bashful=10.0, doc=20.0, dopey=30.0, 
                  grumpy=40, happy=50, sleepy=60, sneezy=70):
         # the usual assign arguments to attributes dance...
         self.bashful = float(bashful)
         self.doc = float(doc)
         self.grumpy = int(grumpy)
         # etc.

Now the constructor can take strings as keywords.  You could even do
something like:

    defaults = { 'bashful':10.0, 'grumpy':20, etc. }

    def __init__(self, **kwargs):
       # check for spurious kwargs
       assert(not(set(kwargs)-set(defaults)))

       for k in defaults:
          v = type(defaults[k])(kwargs[k]) if k in kwargs else defaults[k]
          setattr(self, k, v)



More information about the Python-list mailing list