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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With