metaclass & __slots__

Steve Tregidgo smst at bigfoot.com
Mon Jul 8 11:37:17 EDT 2002


phoebe_1 at att.net (Holden Caulfield) wrote in message news:<c2595393.0207031317.7d9bb013 at posting.google.com>...
> class MX(type):
>     def __init__(cls,name,bases,dict):
>         super(MX,cls).__init__(name,bases,dict)
>         props = {}
>         slots = getattr(cls,'__slots__', [])
>         print slots
>         for v in dict.keys():
>             vs = v.startswith
>             if vs("_get_") or vs("_set_"):
>                 props[v[5:]] = 1
>         for v in props.keys():
>             fget = getattr(cls,"_get_%s" % v, None)
>             fset = getattr(cls,"_set_%s" % v, None)
>             setattr(cls,v,property(fget,fset))
>         slots.append("_%s__%s" % (name,v))
>         setattr(cls,'__slots__',slots)

Holden,

Others have commented on all the groovy metaclass stuff (which I am at
last coming to terms with); I just wanted to point out something I
presume to be a typo in the above code (maybe not in your original,
but in the version I see posted, and which therefore others may be
using).

The indentation of the 'slots.append' line is such that the statement
falls outside of the preceding 'for' loop.  In the example that you
gave, this would not have shown up whilst running the code.

It so happens that in the case where get/set methods exist for exactly
one property, the above code will work as expected (since the 'for'
loop is iterated over just once, and therefore upon finishing the
local name 'v' will be set to the only property).  However, if two or
more properties are defined then only one of them will have the munged
name added to the slots list (whichever ended up being last in
'prop.items()').  If no properties are defined, I would expect the
code to fail with a NameError (probably an UnboundLocalError
actually).

Apologies if the indentation error is an artifact of copying from
editor to mail package; otherwise, consider this a pre-emptive attempt
to answer your next question <wink>.

Cheers,
Steve

-- 
Steve Tregidgo



More information about the Python-list mailing list