Pythonic style
Tim Chase
python.list at tim.thechases.com
Mon Sep 21 10:12:53 EDT 2020
On 2020-09-21 09:48, Stavros Macrakis wrote:
>> def fn(iterable):
>> x, = iterable
>> return x
>
> Thanks, Tim! I didn't realize that you could write (x,) on the LHS!
> Very nice, very Pythonic!
It also expands nicely for other cases, so you want the 3-and-only-3
first values with errors for too many or too few?
x, y, z = iterable
x, y, z = (1, 2, 3)
The (x,) version is just the single case. And it's fast—a single
Python UNPACK_SEQUENCE opcode
>>> dis.dis(fn)
2 0 LOAD_FAST 0 (i)
2 UNPACK_SEQUENCE 1
4 STORE_FAST 1 (x)
3 6 LOAD_FAST 1 (x)
8 RETURN_VALUE
Though now I'm wondering if there's a way to skip the
STORE_FAST/LOAD_FAST instructions and create a function that
generates the opcode sequence
UNPACK_SEQUENCE 1
RETURN_VALUE
:-)
(totally tangential ramblings)
-tkc
More information about the Python-list
mailing list