python/mypy

PEP 572: Type not narrowed correctly in assignment

JelleZijlstra opened this issue · 1 comments

Example from @gvanrossum in #6899:

from typing import Optional

class C:
    def foo(self):
        pass

def good(b: Optional[C]) -> None:
    a = b
    if a:
        a.foo()

def bad(b: Optional[C]) -> None:
    if a := b:
        a.foo()  # E:  Item "None" of "Optional[C]" has no attribute "foo"

This is actually pretty important to support, this example:

discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
    discount = float(mo.group(1)) / 100.0

is the flagship example taken from Python 3.8 What's New, and is actually the prime use case for assignment expressions in general. Raising priority to high.