Python's tuples, dicts, and objects offer the programmer a smooth tradeoff between formality and convenience for small data structures ("things"). For me, the choice of how to represent a thing is dictated mainly by how I'm going to use the structure. In C++, it's a common convention to use struct
for data-only items and class
for objects with methods, even though you can legally put methods on a struct
; my habit is similar in Python, with dict
and tuple
in place of struct
.
For coordinate sets, I'll use a tuple
rather than a point class
or a dict
(and note that you can use a tuple
as a dictionary key, so dict
s make great sparse multidimensional arrays).
If I'm going to be iterating over a list of things, I prefer unpacking tuple
s on the iteration:
for score,id,name in scoreAllTheThings():
if score > goodScoreThreshold:
print "%6.3f #%6d %s"%(score,id,name)
...as the object version is more cluttered to read:
for entry in scoreAllTheThings():
if entry.score > goodScoreThreshold:
print "%6.3f #%6d %s"%(entry.score,entry.id,entry.name)
...let alone the dict
.
for entry in scoreAllTheThings():
if entry['score'] > goodScoreThreshold:
print "%6.3f #%6d %s"%(entry['score'],entry['id'],entry['name'])
If the thing is widely used, and you find yourself doing similar non-trivial operations on it in multiple places in the code, then it's usually worthwhile to make it a class object with appropriate methods.
Finally, if I'm going to be exchanging data with non-Python system components, I'll most often keep them in a dict
because that's best suited to JSON serialization.