Search code examples
pythonpython-3.xtyping

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?


Solution

  • 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