Skip to content

Types not narrowed with constrained TypeVar and walrus #12190

@ghost

Description

Bug Report

It's not entirely clear to me if the existing issues regarding the walrus operator are about the same issue, feel free to close this if they are.

With the following code:

if m := re.search(pattern, string):
    return m.group(group)

I get this error:

Item "None" of "Optional[Match[Any]]" has no attribute "group"  [union-attr]

Even though it's impossible for m to be None, because we just checked its value in the if.

There are no errors with this code:

m = re.search(pattern, string)
if m:
    return m.group(group)

Your Environment

  • Mypy version used: 0.931, mypy 0.940+dev.777885f2c26cce195f6d23c80fefae1e66dfaac2
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
    python_version = '3.8'
    follow_imports = 'silent'
    ignore_missing_imports = true
  • Python version used: 3.8
  • Operating system and version: Debian 11

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-pep-572PEP 572 (walrus operator)topic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions