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()
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.
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.
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.
Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)
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.
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