[Python-Dev] reducing self.x=x; self.y=y; self.z=z boilerplate code

Phillip J. Eby pje at telecommunity.com
Sat Jul 2 01:22:20 CEST 2005


At 03:59 PM 7/1/2005 -0700, Ralf W. Grosse-Kunstleve wrote:
>Hi,
>
>I often find myself writing:
>
>   class grouping:
>
>       def __init__(self, x, y, z):
>           self.x = x
>           self.y = y
>           self.z = z
>
>I hate it, and every time I show this to a Python newcomer I get that
>skeptic look. How about this for a change?
>
>   class grouping:
>
>       def __init__(self, .x, .y, .z):
>           pass

This extends to any number of arguments:

     class grouping:
         def __init__(self, x, y, z):
             self.__dict__.update(locals())
             del self.self

Or if you prefer a more generic approach:

     def initialize(ob, args):
         if 'self' in args:
             del args['self']
         for k, v in args.items():
             setattr(ob,k,v)


     class grouping:
         def __init__(self, x, y, z):
             initialize(self, locals())

There's really no need for special syntax here, if your goal is simply to 
reduce boilerplate.


>I'll write a PEP if I hear a few voices of support.

-1; there are lots of good solutions for this.  For me, I usually have a 
base class with something like this:

     def __init__(self, **kw):
         for k, v in kw.items():
             if not hasattr(self.__class__, k):
                 raise TypeError("%s has no %r attribute" % (self.__class__,k))
             else:
                 setattr(self,k,v)

And then subclasses define their attributes and defaults using class 
attributes, properties, or other descriptors.


>(Otherwise I'll stick to my "adopt_init_args" workaround:
>http://phenix-online.org/cctbx_sources/libtbx/libtbx/introspection.py
>which does a similar job but doesn't look as elegant and is also
>quite inefficient).

There are more efficient solutions, especially __dict__.update().



More information about the Python-Dev mailing list