Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typehinting an unpack assignment [duplicate]

Does anyone know how to properly typehint an unpack assignment - if it's even possible?

To clarify what I mean:

data = some_function_without_typehint()

x: str = data[0]
y: int = data[1]
# x any y have typehint support

x,y = data # no typehint support

# is anything like this possible in v3.8+ ?
x: str, y: int = data
x,y : str, int = data
like image 731
TheClockTwister Avatar asked Sep 15 '25 22:09

TheClockTwister


1 Answers

Variable annotations aren't allowed with unpacking. You have to annotate the names separately from the actual assignment.

x: str
y: str
x, y = data

The rules can be seen in the definition of an annotated assignment

annotated_assignment_stmt ::=  augtarget ":" expression
                               ["=" (starred_expression | yield_expression)]

and the definition of an augtarget:

augtarget                 ::=  identifier | attributeref | subscription | slicing

The lack of multiple targets is explicitly called out:

The difference from normal Assignment statements is that only single target is allowed.


(It's not entirely clear to me why you can't annotate the targets individually. I usually just assume it has something to do with ambiguity and LL(1) grammars. Too much lookahead needed, perhaps, to tell if x: str, y is x annotated with str, y or x annotated with str and y being another target.)

(After typing that, it seems likely. While the new PEG grammar is not so restricted, there may not be a compelling reason to change existing grammar rules to take advantage of it.)

like image 87
chepner Avatar answered Sep 19 '25 16:09

chepner