Nick  Morozov
Nick Morozov

Reputation: 85

How to use Assignment expressions and typing?

PEP-0572 has introduced Assignment expressions feature. And I'm currious how to use it with typing expressions?

Lets take an example from the PEP's page:

if result := solution(xs, n):
    # use result

And add type of value that we want to use:

from typing import Dict
if result:Dict := solution(xs, n):
    # use result

It will fail with SyntaxError.

Is there way to use typing for such expressions?

Upvotes: 2

Views: 158

Answers (1)

Andrew Jaffe
Andrew Jaffe

Reputation: 27097

The PEP explicitly says:

Inline type annotations are not supported:

p: Optional[int] = None

# Closest equivalent is p: Optional[int] as a separate declaration

So, for your example:

from typing import Dict

result: Dict
if result := solution(xs, n):
    # use result

Upvotes: 6

Related Questions