Skip to content

Narrowing and exhaustiveness errors when matching on a tuple of optionals #14731

Open
@linabutler

Description

@linabutler

Bug Report

When using match on a tuple of optionals, Mypy doesn't seem to:

  1. Narrow the type from Optional[T] to T in non-optional cases, even if all the None cases have been handled.
  2. Recognize that the match is exhaustive.

This feels similar to #12267 (comment), or maybe #12364 or #13989, but the example is a little different; apologies if it's a dupe / already known—and thanks for taking a look!

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=b6c10a27006d7b5ad55729467c2c5de8

Expected Behavior

No errors. 😊

I've used this match-on-a-tuple pattern in Rust and Swift a few times, which is why I was a little surprised that Mypy didn't like it.

Actual Behavior

main.py:4: error: Missing return statement  [return]
main.py:9: error: Item "None" of "Optional[str]" has no attribute "encode"  [union-attr]

Your Environment

  • Mypy version used: 1.0.0
  • Python version used: 3.11

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions