Suggestions for good programming practices?

Jeff Epler jepler at unpythonic.net
Tue Jun 25 09:34:14 EDT 2002


On Tue, Jun 25, 2002 at 07:48:06AM -0400, Roy Smith wrote:
> "David LeBlanc" <whisper at oz.net> wrote:
> > Structs and tuples are different. They're both of the same general category
> > of aggregate data, but they are different as Brian notes.
> 
> I've come to really dislike using tuples for data structures, and 
> instead create small data classes.  Even if the class is no more 
> complicated than:
> 
> class myData:
>    def __init__ (self, foo, bar):
>       self.foo = foo
>       self.bar = bar
> 
> you've added quite a bit of functionality.  First, the code becomes a 
> little more self-documenting.  "power = ckt.volts * ckt.amps" is a lot 
> easier to read and understand than "power = ckt[0] * ckt[1]".

(the following applies most obviously to modern versions of python.  I
use subclassing of builtin objects, __slots__ and zip().  Even so, the
myStruct class is useful in any version of Python back to at least 1.5,
if you make myStruct a regular class, and include a definition
of zip())

You can do even better (lower memory overhead) with
    class myData(object):
	__slots__ = ['foo', 'bar']
        def __init__ (self, foo, bar):
            self.foo = foo
            self.bar = bar

you could go a little farther and make a superclass that has a __init__
that works for any subclass:
    class myStruct(object):
	def __init__(self, *args):
	    if len(args) != len(self.__slots__):
		raise TypeError, \
		    "__init__() takes exactly %d arguments (%d given)" \
		    % (len(self.__slots__)+1, len(args)+1)
	    for name, arg in zip(self.__slots__, args):
		setattr(self, name, arg)

    class myData(myStruct):
	__slots__ = ['foo', 'bar']

Jeff





More information about the Python-list mailing list