Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decide when to introduce a new type instead of using list or tuple?

Tags:

python

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.

like image 403
Serge Avatar asked Jul 23 '12 08:07

Serge


1 Answers

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.

like image 141
ecatmur Avatar answered Nov 28 '22 00:11

ecatmur