15

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

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

How can I do this?

rkoni
  • 151
  • 3

2 Answers2

14

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():
    ...
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Is the `= 0` necessary? It seems like `var: int` would be enough. – Warren Weckesser Jun 03 '21 at 20:15
  • 1
    If you don't initialize it with an integer, you need `var: Optional[int]` so it doesn't violate the type. – Barmar Jun 03 '21 at 20:18
  • 1
    Interesting. `var: int` doesn't actually create `var`, so it never has the value `None`. Why would the type be violated? – Warren Weckesser Jun 03 '21 at 20:28
  • I was just going by what the PEP said. It suggested `var: Optional[int] = None` – Barmar Jun 03 '21 at 20:30
  • 2
    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`. – chepner Jun 04 '21 at 11:39
2

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 !':='
chepner
  • 497,756
  • 71
  • 530
  • 681
  • this seems like an oversight? I would expect that this operator would be implemented with proper typing – rkoni Jun 03 '21 at 23:00
  • 2
    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. – chepner Jun 04 '21 at 11:34
  • 1
    The walrus operator seems like an incomplete/flawed concept if it can't even be used with instance variables and type hints. – 303 Apr 26 '22 at 11:54