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

Josiah Carlson jcarlson at uci.edu
Sat Jul 2 09:12:48 CEST 2005


"Ralf W. Grosse-Kunstleve" <rwgk at cci.lbl.gov> wrote:
> Josiah Carlson wrote:
> > 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.
> 
> Where? The meta-class idea sounds interesting. Could you work it out?

I had assumed that you were a 'go-getter', and that you would want to
figure it out yourself.  Apparently I was wrong.

Being that I don't use metaclasses (I don't need the functionality), I
had to spend 10 minutes learning about them, and 5 minutes implementing
the following.

class AutoSlots(type):
    def __init__(cls, name, bases, dct):
        slots = dict.fromkeys(dct.get('__slots__', []))
        if '__init__' in dct:
            init = dct['__init__']
            ifvn = init.func_code.co_varnames
            for i in xrange(init.func_code.co_argcount):
                x = ifvn[i]
                if x[:1] == '_'and x[1:] not in slots:
                    slots[x[1:]] = None
        if slots:
            dct['__slots__'] = slots.keys()
        super(AutoSlots, cls).__init__(name, bases, dct)

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

class Foo(object):
    __metaclass__ = AutoSlots
    def __init__(self, a, b, _x, _y=None):
        InitSlots(self, locals())

>>> foo = Foo(1,2,3)
>>> vars(foo)
{'y': None, 'x': 3}


> > A syntax change is wholly unnecessary.
> 
> I wonder why everybody gets so agitated about a syntax enhancement
> proposal. I am not proposing a syntax change!

Yes you are.  Any thing that changes syntax, necessarily is a syntax
change.  People get "agitated" because with every syntax addition, that
is just another syntax that a newbie may need to learn in order to
understand some block of code.  Further, for those of us who try to
teach about it, it is just one more little nit that students ask about.

Considering that EVERYTHING you want is possible with 17 lines of
support code (which can be tossed into site and assigned to __builtins__),
and 2 lines of boilerplate (which can be made into one metaclass line if
you are willing to do a bit more work), a syntax change is foolishness.


> I know enhancing the syntax is work, but shouldn't a syntax leading to
> less code clutter be the higher value?

Why bother if the non-syntax-change goes 99% of the way?  I've further
pushed myself to -10 for any syntax change offering during my
implementation of AutoSlots.

 - Josiah



More information about the Python-Dev mailing list