How to set object parameters nicely?

Lie Ryan lie.1296 at gmail.com
Thu Dec 3 09:16:50 EST 2009


On 12/2/2009 10:26 AM, allen.fowler wrote:
> I've tried this, but have found two issues:
>
> 1) I can't set default values.
> 2) I can't set required values.
>
> In both of the above cases, if the object is created without the
> "exact" dict() I expect, all the assumption my methods make about what
> is available in "self" fall apart.
>

You can inspect the dict, something like:

def __init__(self, **kwargs):
     required = ['p1', 'p2', 'p3']
     optional = {'p4': 'foo', 'p5': 'bar'}
     if any(par not in kwargs for par in required):
         raise TypeError('required parameter not set')
     for par in optional:
         if par not in kwargs:
             kwargs[par] = optional[par]
     # ... do work ...

Tips: turn this parameter checker into a @decorator

But generally, as Diez pointed out your class may be doing too much. Try 
splitting it into smaller classes. Passing too much parameter is an 
indication of a God Object (or demi-god) 
http://en.wikipedia.org/wiki/God_object "He" just knows too much.



===

Unpythonic warning: Java-style code would use several separate 
initializers that would be called in order before the object is in a 
ready state (but never in an invalid state [!]). The first initializer 
merely set all the attributes into some valid state. This is an 
*anti-pattern* in python. Avoid it.

def __init__(self):
     self.p1 = ''
     self.p2 = 0
     self.p3 = []
def init_name(self, name):
     self.p1 = name

etc, etc...

===



More information about the Python-list mailing list