Suggestions for good programming practices?
Roy Smith
roy at panix.com
Tue Jun 25 07:48:06 EDT 2002
"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]".
Secondly, it makes it easier to catch programming errors. I was working
with somebody the other day who was using tuples to store data. His
program was doing something strange. When I made him rewrite one of his
data structures as a simple data class instead of a tuple, the reason
instantly popped out. He had gotten confused and was using the wrong
piece of data. When he had everything as tuples, it just happily took
the i'th element of the wrong tuple and gave him garbage. But, when he
tried to access an attribute that didn't exist, it immediately raised an
exception.
More information about the Python-list
mailing list