How to type hint with walrus operator?

2.8k Views Asked by At

I am trying to type hint a walrus operator expression, i.e.

while (var: int := some_func()): ...

How can I do this?

2

There are 2 best solutions below

5
On

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():
    ...
3
On

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 !':='