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

Josiah Carlson jcarlson at uci.edu
Sat Jul 2 03:31:20 CEST 2005


Nick Coghlan <ncoghlan at gmail.com> wrote:
> Jp Calderone wrote:
> > If you use vars(self).update(locals()), it even looks halfway
> > pleasant ;)  I'm not sure what python-dev's current opinion of
> > vars(obj) is though (I'm hoping someone'll tell me).
> > 
> > Of course, both of these fall over for __slots__'ful classes.  It'd
> > be nice if there were a general way to deal with attributes of an
> > instance, regardless of the implementation details of its memory
> > layout.
> 
> That's where PJE's more generic approach comes in:
> 
>       def initialize(ob, args, excluded=['self']):
>           for k in excluded:
>               if k in args:
>                   del args[k]
>           for k, v in args.items():
>               setattr(ob,k,v)
> 
>       class grouping:
>           def __init__(self, x, y, z):
>               initialize(self, locals())

I'm with everyone else on this, -1 on .x syntax.  As provided in the 6
line function above, everything desired is available.

You want something that you don't need to use the excluded argument for,
but still has the same stench as what Ralf originally offered?

      def initialize(ob, args):
          for k, v in args.items():
              if k[:1] == '_':
                  setattr(ob,k[1:],v)

      class grouping:
          def __init__(self, _x, _y, _z):
              initialize(self, locals())

Now, don't get me wrong, definining __slots__ can be a pain in the
tookus, but with a proper metaclass, that metaclass can define the
__slots__ attribute based on the argument list for __init__().

There you go.  A syntax change is wholly unnecessary.

 - Josiah



More information about the Python-Dev mailing list