__slots__ from metaclass (was Re: Python vs. Lisp: scope issues)

Alex Martelli aleax at aleax.it
Thu Oct 16 10:27:52 EDT 2003


Bengt Richter wrote:
   ...
>   class Accumulator(object):
>       __slots__ = ['n']
>       def __init__(self, n=0): self.n = n
>       def __call__(self, n): self.n +=n; return self.n
> 
>   a = Accumulator()
> 
> 
> BTW, can you plug in a __slots__ in the class dict via a metaclass and
> have it take effect, or is that too late? IWT you could, but the class
> body definition has already been executed and its elements bound in a
> dict, so will that dict be converted after the metaclass mod to a slotted
> version?

type.__new__ is what normally applies '__slots__', if found in the
class dict.  So, it is necessary and sufficient for your own metaclass's
__new__ to insert the '__slots__' you want to have before delegating
the rest of the operation to type.__new__.  My presentation on
metaclasses at http://www.strakt.com/docs/ep03_meta.pdf (which I just
found out has the mistaken title "The Template DP in Python", from
_another_ presentation I gave at the same conference -- ouch) gives
an example of a custom metaclass injecting __slots__ apropriately.


Alex





More information about the Python-list mailing list