views:

267

answers:

1

This is an unusual question, but I'd like to dynamically generate the slots attribute of the class based on whatever attributes I happened to have added to the class.

For example, if I have a class:

class A(object):
    one = 1
    two = 2

    __slots__ = ['one', 'two']

I'd like to do this dynamically rather than specifying the arguments by hand, how would I do this?

+4  A: 

At the point you're trying to define slots, the class hasn't been built yet, so you cannot define it dynamically from within the A class.

To get the behaviour you want, use a metaclass to introspect the definition of A and add a slots attribute.

class MakeSlots(type):

    def __new__(cls, name, bases, attrs):
        attrs['__slots__'] = attrs.keys()

        return super(MakeSlots, cls).__new__(cls, name, bases, attrs)

class A(object):
    one = 1
    two = 2

    __metaclass__ = MakeSlots
Jarret Hardie