Skip to content

Exhaustiveness check is not run for functions returning None #17141

Closed as not planned
@tobiasBora

Description

@tobiasBora

Bug Report

https://peps.python.org/pep-0622/#exhaustiveness-checks specifies that an error should occur if a case is forgotten in a match clause. Yet, this does not work if the return type is None, i.e. for functions having only side effects like:

# Execute with "python foo.py" and
# run the type checking with "mypy --strict foo.py"


### Define our types

# See https://github.com/python/mypy/issues/17139 to get a nicer
# syntax once the bug is solved

class Mult:
    # Expr is not yet defined, so we use forward references
    # https://peps.python.org/pep-0484/#forward-references
    left: 'Expr'
    right: 'Expr'
    def __init__(self, left:'Expr', right:'Expr'):
        self.left = left
        self.right = right

class Add:
    # Expr is not yet defined, so we use forward references
    # https://peps.python.org/pep-0484/#forward-references
    left: 'Expr'
    right: 'Expr'
    def __init__(self, left:'Expr', right:'Expr'):
        self.left = left
        self.right = right

class Const:
    val: int
    def __init__(self, val:int):
        self.val = val

Expr = Const | Add | Mult

### Define our functions
x = 0

def my_eval(e : Expr) -> None:
    match e:
# This case is missing, it should give an error
#        case Const():
#            print(e.val)
        case Add():
            print("(")
            my_eval(e.left)
            print(") + (")
            my_eval(e.right)
            print(")")
        case Mult():
            print("(")
            my_eval(e.left)
            print(") + (")
            my_eval(e.right)
            print(")")

### Use them

my_eval(Add(Const(42),Const(45)))

To Reproduce

Gist URL: https://gist.github.com/mypy-play/c639245b119bb649b19942f0e05ea65b
Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=c639245b119bb649b19942f0e05ea65b

Expected Behavior

This should produce an error (ideally with an example of a case/type that is not matched).

Actual Behavior

No error.

Your Environment

  • Mypy version used: 1.5.1
  • Mypy command-line flags: none or strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-match-statementPython 3.10's match statement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions