I am trying to type hint a walrus operator expression, i.e.
while (var: int := some_func()): ...
How can I do this?
I am trying to type hint a walrus operator expression, i.e.
while (var: int := some_func()): ...
How can I do this?
It's not possible. From PEP 572
Inline type annotations are not supported:
You need to declare the variable before the while
loop, and you can specify the type there.
var: int
while var := some_func():
...
var: Optional[int]
so it doesn't violate the type. –
Fukuoka var: int
doesn't actually create var
, so it never has the value None
. Why would the type be violated? –
Brennen var: Optional[int] = None
–
Fukuoka Optional
hint is required; it's just the one used as an example. var: int
alone should be fine, as long as some_func
is guaranteed to return an int
. –
Protonema I don't believe you can.
A variable can be annotated because the grammar rule for assignment is
assignment:
| NAME ':' expression ['=' annotated_rhs ]
...
Note that the type hint is explicit between the :
following the name and the =
.
An assignment expression, on the other hand, only provides for a name, no type hint, preceding the :=
:
named_expression:
| NAME ':=' ~ expression
| expression !':='
if x: int := f(y):
can't be expressed with an LL(1) grammar; the lookahead needed to tell if the :
following the x
introduces a type hint or finishes the condition simply isn't available to an LL(1) parser. Python now uses a PEG parser, which I think is much more flexible, but :=
predates the introduction of the new parser. –
Protonema © 2022 - 2025 — McMap. All rights reserved.
= 0
necessary? It seems likevar: int
would be enough. – Brennen