Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiom for long tuple unpacking [closed]

Tags:

Scenario: you have a long tuple as a result of a SQL query and want to unpack it into individual values. What's the best way to do that while conforming to PEP8? So far I have these three options:

  1. single assignment, use backslash to split to multiple lines

    person_id, first_name, last_name, email, \     birth_date, graduation_year, home_street, \     home_city, home_zip, mail_street, mail_city, \     mail_zip = row 
  2. single assignment, group left-hand side in parantheses and break lines without a backslash

    (person_id, first_name, last_name, email,     birth_date, graduation_year, home_street,     home_city, home_zip, mail_street, mail_city,     mail_zip) = row 
  3. split into multiple assignments, each fitting into a single line

    person_id, first_name, last_name, email = row[0:4] birth_date, graduation_year, home_street = row[4:7] home_city, home_zip, mail_street, mail_city = row[7:11] mail_zip = row[11] 

Which of the three options is the best? Is there anything better?

like image 241
koniiiik Avatar asked Sep 25 '14 10:09

koniiiik


People also ask

What is unpacking of tuple?

Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable.

What is packing and unpacking in tuples?

Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.

What does unpacking mean in Python?

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

How do I unpack a tuple in a for loop?

We can do the tuple unpacking right inside the for loop itself because anything you can put on the left-hand side of the equal sign, you can put in between the for and the in in a for loop. This is the most common place you'll see tuple unpacking used: on the first line of a for loop.


1 Answers

Anwering your question "Which of the three options is the best?"

pep8 states:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

This Means the second one is preferred over the first one. The third one is fine conforming pep8 as well, though personally wouldn't recommend it.

like image 187
Remco Haszing Avatar answered Sep 20 '22 14:09

Remco Haszing