I like to do some silly stuff with python like solving programming puzzles, writing small scripts etc. Each time at a certain point I'm facing a dilemma whether I should create a new class to represent my data or just use quick and dirty and go with all values packed in a list or tuple. Due to extreme laziness and personal dislike of self
keyword I usually go with the second option.
I understand than in the long run user defined data type is better because path.min_cost
and point.x, point.y
is much more expressive than path[2]
and point[0], point[1]
. But when I just need to return multiple things from a function it strikes me as too much work.
So my question is what is the good rule of thumb for choosing when to create user defined data type and when to go with a list or tuple? Or maybe there is a neat pythonic way I'm not aware of?
Thanks.
Are you aware of collections.namedtuple
? (since 2.6)
def getLocation(stuff):
return collections.namedtuple('Point', 'x, y')(x, y)
or, more efficiently,
Point = collections.namedtuple('Point', 'x, y')
def getLocation(stuff):
return Point(x, y)
namedtuple
can be accessed by index (point[0]
) and unpacked (x, y = point
) the same way as tuple
, so it offers a nearly painless upgrade path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With