12/3/2023 0 Comments Tuple unpacking![]() Since Python 3.8 (see item 7 on this list), the generalized syntax discussed above is now valid. Here this is not the case, as leaving out the parentheses does not produce some other unwanted behavior, but rather no behavior at all. The unpack operation can take place, inline, in the python evaluation loop, while the subscription call requires looking up of the function on the tuple object to retrieve the value, using. It's of course no big deal to have to place parentheses around the return value, but usually additional parentheses are only needed to distinguish between several possible outcomes (grouping). The tuple unpacking operation is a simple bytecode (UNPACKSEQUENCE), while the indexing operation has to call a method on the tuple (BINARYSUBSCR). ![]() In this case though, this leads to the invalid code def f(): Normally when I have code like this, I consider t to be a temporary name, which I ought to be able to get rid of simply be replacing t in the bottom line with its definition. Consider the following (also valid) solution: def f(): Problem (from Python Cookbook) You have an N-element tuple that you would like to unpack into a collection of N variables. This breaks an important contract I thought I had with the Python language. Have this case simply been forgotten by the Python developers, or are there any reason why this case is invalid syntax? Why I care Is indeed legal and results in the same with and without parentheses. The fact that I use this in a return statement seems to be important, as t = 1, *rest I can make it work by encapsulating the returned tuple in parentheses like so: def f(): ![]() As so, I was surprised to discover that the following is invalid syntax in Python 3.6 (and remains so in Python 3.7): def f(): PEP 3132 and PEP 448), allowing it to be used in more and more circumstances. Over the years, this unpacking has been gradually generalized (see e.g. The Python language (especially 3.x) allows very general unpacking of iterables, a simple example of which is a, *rest = 1, 2, 3
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |