Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit class with weakref in slots

I tried to use weak references on my classes, where I use slots to save some memory, but I wasn't able to make derived class.

class A(object):
    __slots__ = ['__weakref__']

class B(A):
    __slots__ = A.__slots__ + ['foo']
#TypeError: Error when calling the metaclass bases
#    __weakref__ slot disallowed: either we already got one, or __itemsize__ != 0

Where's the trick? I didn't find any solution. I'm using python 2.7.3.

like image 393
ziima Avatar asked Sep 05 '25 01:09

ziima


1 Answers

In derived classes you should not put slots that were defined in the base classes.

In fact the error says:

TypeError: Error when calling the metaclass bases __weakref__ slot disallowed: either we already got one, or __itemsize__ != 0

Simply use:

class B(A):
    __slots__ = ['foo']

This is explained in the documentation for__slots__:

The action of a __slots__ declaration is limited to the class where it is defined. As a result, subclasses will have a __dict__ unless they also define __slots__ (which must only contain names of any additional slots).

like image 66
Bakuriu Avatar answered Sep 06 '25 21:09

Bakuriu