How to type hint with walrus operator?
Asked Answered
A

2

19

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

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

How can I do this?

Acerbate answered 3/6, 2021 at 20:6 Comment(0)
F
20

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():
    ...
Fukuoka answered 3/6, 2021 at 20:9 Comment(5)
Is the = 0 necessary? It seems like var: int would be enough.Brennen
If you don't initialize it with an integer, you need var: Optional[int] so it doesn't violate the type.Fukuoka
Interesting. var: int doesn't actually create var, so it never has the value None. Why would the type be violated?Brennen
I was just going by what the PEP said. It suggested var: Optional[int] = NoneFukuoka
I don't think the 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
P
3

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 !':='
Protonema answered 3/6, 2021 at 20:12 Comment(3)
this seems like an oversight? I would expect that this operator would be implemented with proper typingAcerbate
Python's grammar is intentionally restricted so that it can be parsed by an LL(1) parser. I'm fuzzy on the details (it's been a long time since I've studied parsers), but I think something like 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
The walrus operator seems like an incomplete/flawed concept if it can't even be used with instance variables and type hints.Silvanasilvano

© 2022 - 2025 — McMap. All rights reserved.