Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python does not allow annotating the types of variables when unpacking

PEP 526 says the following:

Note that, although the syntax does allow tuple packing, it does not allow one to annotate the types of variables when tuple unpacking is used.

Why does python not support type annotations of variable while unpacking? PS. I am having to annotate the types first and then do the unpacking which is fine, except that annotating while unpacking would have been neater.

like image 463
rohitjv Avatar asked Dec 02 '19 21:12

rohitjv


People also ask

What is unpacking variables in Python?

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

What is variable annotation in Python?

Variable annotations are just the next step from # type comments, as they were defined in PEP 484 ; the rationale behind this change is highlighted in the respective section of PEP 526. So, instead of hinting the type with: primes = [] # type: List[int]

What is __ annotations __ in Python?

Annotations were introduced in Python 3.0 originally without any specific purpose. They were simply a way to associate arbitrary expressions to function arguments and return values. Years later, PEP 484 defined how to add type hints to your Python code, based off work that Jukka Lehtosalo had done on his Ph. D.

How do you specify variable type in Python?

Specify a Variable Type Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)


1 Answers

There is some information about this in the Rejected/Postponed Proposals section of PEP 526:

Allow type annotations for tuple unpacking: This causes ambiguity: it's not clear what this statement means:

x, y: T

Are x and y both of type T, or do we expect T to be a tuple type of two items that are distributed over x and y, or perhaps x has type Any and y has type T? (The latter is what this would mean if this occurred in a function signature.) Rather than leave the (human) reader guessing, we forbid this, at least for now.

The comment seems to suggest there may eventually be a proposal for a simpler syntax that isn't as prone to being misconstrued. For now, we're left with having to annotate the tuple's types separately.

like image 51
Ben Siver Avatar answered Sep 19 '22 11:09

Ben Siver