Friday, January 9, 2009

Python class slots

Today I came over __slots__ feature of Python. It's used to define the list of possible attributes at the class creation time, so by default no dictionary is kept for every instance. This can save memory, if such instances are stored in big lists. To use slots, class should be defined like this:
class Point(object):
  __slots__=["x","y"]
The next example demonstrates the difference between a class with slots and a regular class.
class OldPoint(object):
  pass

p=OldPoint()
p.x=10
p.y=20   # these are OK
p.z=30   # this is OK as well - any attributes are allowed

p=Point()
p.x=10
p.y=20   # this are OK
p.z=30   # this causes AttributeError: 'Point' object has no attribute 'z'
Defining __slots__ affects not only the dictionary of the instances, but also the way they are serialized (or pickled in Python terminolodgy). Also a weak reference (__weakref__) is not enabled by default (can be overriden)

Links

No comments: