Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting tuples in Python - best practice?

Tags:

python

tuples

I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)

For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job

I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?

Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields

or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)

like image 318
andygeers Avatar asked Sep 03 '08 13:09

andygeers


4 Answers

@Staale

There is a better way:

job = dict(zip(keys, values))
like image 60
Aaron Maenpaa Avatar answered Oct 14 '22 17:10

Aaron Maenpaa


I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.

For example:

job={}
job['jobid'], job['label'], job['username']=<querycode>
like image 39
Chris Upchurch Avatar answered Oct 14 '22 16:10

Chris Upchurch


This is an old question, but...

I'd suggest using a named tuple in this situation: collections.namedtuple

This is the part, in particular, that you'd find useful:

Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute.

like image 20
JAB Avatar answered Oct 14 '22 18:10

JAB


Perhaps this is overkill for your case, but I would be tempted to create a "Job" class that takes the tuple as its constructor argument and has respective properties on it. I'd then pass instances of this class around instead.

like image 35
Ryan Duffield Avatar answered Oct 14 '22 17:10

Ryan Duffield