Skip to content

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

Closed

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

Activity

  1. fluggo commented on Jan 6, 2020

    @fluggo
    Author

    This might be the same bug as #7316.

  2. added 2 commits that reference this issue on Jan 9, 2020
    b844526
    29db473
  3. msullivan commented on Feb 28, 2020

    @msullivan
    Collaborator

    Closing in favor its duplicate #8447 which is about to be fixed anyway

  4. hauntsaninja commented on Sep 27, 2020

    @hauntsaninja
    Collaborator

    @fluggo I was wondering if the code you're working on is open source? My interest is in adding projects to https://github.com/hauntsaninja/mypy_primer that use newer Python features.

  5. fluggo commented on Sep 28, 2020

    @fluggo
    Author

    @hauntsaninja Sorry, this project wasn't. I appreciate the ask, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions