Which uses less memory?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Nov 18 12:20:14 EST 2007


En Sat, 17 Nov 2007 19:30:04 -0300, Nick Craig-Wood <nick at craig-wood.com>  
escribi�:

>>  I'm working on an application that is very memory intensive, so we're
>>  trying to reduce the memory footprint of classes wherever possible.  I
>
> I'd guess that if you __slot__-ed the Domain class then you'll find
> the overhead of a type attribute is minimal (4 bytes per instance I
> think).
>
> No idea about Hessian or Stomp (never heard of them!) but classes with
> __slot__s are normal classes which would pickle or unpickle.

Actually classes with __slots__ require that you write your own  
__getstate__ and __setstate__. The following implementation may be enough  
in simple cases:

py> class X(object):
...     __slots__ = ('foo','bar')
...
py> x = X()
py> x.foo = 123
py> dumps(x)
Traceback (most recent call last):
...
TypeError: a class that defines __slots__ without defining __getstate__  
cannot b
e pickled

class X(object):
     __slots__ = ('foo','bar')
     def __getstate__(self):
         return dict((name, getattr(self, name))
           for name in self.__slots__
           if hasattr(self, name))
     def __setstate__(self, state):
         for name,value in state.iteritems():
             setattr(self, name, value)

py> x = X()
py> x.foo = 123
py> p = dumps(x)
py> x2 = loads(p)
py> type(x2)
<class '__main__.X'>
py> x2.foo
123
py> x2.bar
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: bar

-- 
Gabriel Genellina




More information about the Python-list mailing list