This post originated from an RSS feed registered with Python Buzz
by Ben Last.
Original Post: The Nagging Doubts
Feed Title: The Law Of Unintended Consequences
Feed URL: http://benlast.livejournal.com/data/rss
Feed Description: The Law Of Unintended Consequences
Tuples, asserts Guido, are for heterogenous data. The C programmer I used to be would, of course, throw together a struct (almost certainly typedef'd) to be the equivalent. As that same C programmer I was burned sufficiently often by rogue constants and editing errors to adopt a firm rule of thumb; if I could avoid hard-wiring of constants, I would. This extended such that wherever possible, my code would be controlled by constants #defined at the top of the source file; change those, and the code changed with them.
Which brings me back to tuples. Imagine that I construct a tuple thusly, to represent, say, a book on Amazon:
record = (author, title, ISBN, price)
To access it, I can write code like:
print "Author is %s" % record[0]
Yet the C-programmer-within spots that stray [0] and nags me: "rogue hardwired constant!". There's a strong urge to replace it with a constant, something like:
AUTHOR=0
TITLE=1
print "Author is %s, Title is %s" % (record[AUTHOR], record[TITLE])
Yet even that doesn't satisfy him; he worries that someone will write an assignment to the tuple and inadvertently transpose a couple of elements. There is, he says, no way to hardwire the relationship between the order in which items are stuffed into a tuple and the indexes used to retrieve them.
To which I say; well, if you're that worried use an object. Yet still I find those stray remaining indexes... disturbing.
Just now I wrote (apropos of some database code):
# Read a record, take the first element, strip off whitespace and lower-case it.
value = cr.readone()
if value and value[0]: return value[0].strip().lower().split()
Now that really sets off the deep, C-derived danger instincts. What, he cries, if anything were to return NULL in that wild and assumptive sequence of function calls? I think I need to go and make him a cup of tea and settle his nerves; he's still not entirely used to exceptions.