Skip to content

Type guard in list comprehension with assignment expression does not constrain type #8236

Closed
@fluggo

Description

@fluggo
  • Are you reporting a bug, or opening a feature request? Bug
from typing import List, Iterator
import os
import re
    
def get_schema_versions(self) -> List[int]:
    return [int(match.group(0))
        for filename in os.listdir('schema')
        if (match := re.fullmatch(r'(\d+)\.sql', filename)) is not None]

def get_schema_versions2(self) -> Iterator[int]:
    for filename in os.listdir('schema'):
        match = re.fullmatch(r'(\d+)\.sql', filename)

        if match is not None:
            yield int(match.group(0))
  • What is the actual behavior/output?

In the first function, mypy interprets the match variable as Optional[Match[str]] and flags the use of the possibly-None object. In the second function, match under the if statement is considered Match[str].

  • What is the behavior/output you expect?

Since both statements guard the match variable against being None, both uses should be of type Match[str].

  • What are the versions of mypy and Python you are using? mypy 0.761, Python 3.8
    Do you see the same issue after installing mypy from Git master? Don't know how
  • What are the mypy flags you are using? (For example --strict-optional) Nothing relevant

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions