Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hints when unpacking a tuple?

Is it possible to use type hinting when unpacking a tuple? I want to do this, but it results in a SyntaxError:

from typing import Tuple  t: Tuple[int, int] = (1, 2) a: int, b: int = t #     ^ SyntaxError: invalid syntax 
like image 956
Cai Avatar asked Aug 29 '18 17:08

Cai


People also ask

What is unpacking of tuple?

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

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.

How do I unpack a list of tuples?

If you want to unzip your list of tuples, you use the combination of zip() method and * operator.

How does tuple unpacking work in Python?

Unpacking Tuples When we put tuples on both sides of an assignment operator, a tuple unpacking operation takes place. The values on the right are assigned to the variables on the left according to their relative position in each tuple . As you can see in the above example, a will be 1 , b will be 2 , and c will be 3 .


1 Answers

According to PEP-0526, you should annotate the types first, then do the unpacking

a: int b: int a, b = t 
like image 60
Patrick Haugh Avatar answered Sep 22 '22 06:09

Patrick Haugh