Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readable convention for unpacking single value tuple

There are some related questions about unpacking single-value tuples, but I'd like to know if there is a preferred method in terms of readability for sharing and maintaining code. I'm finding these to be a source of confusion or misreading among colleagues when they involve a long function chain such as an ORM query.

Is there some convention for this similar to the pep8 guidelines? If not, which is the clearest, most readable way to do it?

Below are the ways I've tried, and my thoughts on them.

Two common methods that are neat but easy to miss:

value, = long().chained().expression().that().returns().tuple()

value = long().chained().expression().that().returns().tuple()[0]

A function would be explicit, but non-standard:

value = unpack_tuple(long().chained().expression().that().returns().tuple())

Maybe always commenting would be the most clear?

# unpack single-value tuple
value, = long().chained().expression().that().returns().tuple()
like image 511
Ian Mackinnon Avatar asked Sep 15 '10 20:09

Ian Mackinnon


People also ask

Can tuple be a single value?

Create a Tuple with a Single Value (Singleton)To store a single value, or singleton in a tuple, you must include a comma when assigning the value to a variable. If you don't include the comma, Python does not store the value as a tuple. For example, create the following tuple to store a single string.

Is unpacking possible in a tuple?

In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.

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 unpacking of tuple give example?

Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)


1 Answers

How about using explicit parenthesis to indicate that you are unpacking a tuple?

(value, ) = long().chained().expression().that().returns().tuple()

After all explicit is better than implicit.

like image 71
Manoj Govindan Avatar answered Sep 22 '22 03:09

Manoj Govindan