Inheritable Slots Metaclass

Rebel Lion r3831110n at gmail.com
Wed May 26 08:49:37 EDT 2010


I made a metaclass to inherit __slots__ automatically.

I think this feature should be included in builtin object's metaclass.

You can now write:

    class Foo(object):
        __metaclass__ = SlotMetaclass

        @slot
        def foo():
            pass


    class Bar(Foo):

        @slot
        def bar():
            pass

    foo = Foo()
    foo.foo = 1
    bar = Bar()
    bar.bar = 1
    bar.foo = 1
    try:
        bar.baz = 1 # this should fall
    except AttributeError, e:
        print 'yeah', e


Instead of

    class Foo(object):
          __slots__ = ['foo']
    class Bar(Foo)
          __slots__ = ['foo', 'bar']


Please discuss the pros & cons for this feature.


Here is the metaclass:

class slot(object):
    """Slot Decorator"""

    def __init__(self, func):
        pass


class SlotMetaclass(type):
    """Inheritable Slots Metaclass"""

    def __new__(cls, name, bases, attrs):
        # make a normal class, and get its attributes to decide which
ones are slots
        tmpcls = type.__new__(cls, name, bases, attrs)
        slots = []
        for k in dir(tmpcls):
            v = getattr(tmpcls, k)
            if isinstance(v, slot):
                slots.append(k)
        # clean up
        del tmpcls
        for x in slots:
            del attrs[x]
        # create the real class with __slots__
        attrs['__slots__'] = slots
        return type.__new__(cls, name, bases, attrs)







More information about the Python-list mailing list