[CentralOH] __slots__

Mark Erbaugh mark at microenh.com
Mon Apr 14 16:23:03 CEST 2008


I am implementing a class to handle data retrieved from a PostgreSQL
database using psycopg2.

>From the Python Language Reference Manual:

"By default, instances of both old and new-style classes have a
dictionary for attribute storage. This wastes space for objects having
very few instance variables. The space consumption can become acute when
creating large numbers of instances."

In my application, there is an instance for each row returned from a SQL
query, so it seems that __slots__ might be helpful.

However, to use the instance to update the data on the server, you need
a dict as the parameter passing is done with dictionary syntax:

cursor.execute('update table set field=%(f1)s', {'f1':f1val})


If the class doesn't use __slots__, you can just use the instance's
__dict__ data member.

I could add a method to the class to return a suitable dict, but would
that be less overhead than skipping __slots__ altogether?  There will be
more times that data is retrieved than updated, so this method won't be
called on each instance created.

Or is there a better way?

Thanks,
Mark






More information about the CentralOH mailing list