Skip to content

Incorrect inference of types when using match/case on a caught exception #9259

@macdjord

Description

@macdjord

Bug description

In the following example, on line 20, Pylint complains that "Instance of 'Base' has no 'child_field' member". The correct inferred type of variable ex is Child, not Base, due to being inside the case statement on line 18.

class Base(Exception):
    def __init__(self):
        super().__init__()
        self.common_field = ""


class Child(Base):
    def __init__(self):
        super().__init__()
        self.child_field = ""


def foo() -> str:
    try:
        pass
    except Base as ex:
        match ex:
            case Child():
                # noinspection PyUnresolvedReferences
                return ex.child_field
            case _:
                return ex.common_field


def bar(ex: Base) -> str:
    match ex:
        case Child():
            # noinspection PyUnresolvedReferences
            return ex.child_field
        case _:
            return ex.common_field

Curiously, no warning is emitted on line 29; in that case, the type is inferred correctly.

Command used

pylint test2.py

Pylint output

$ pylint test2.py
************* Module test2
test2.py:1:0: C0114: Missing module docstring (missing-module-docstring)
test2.py:1:0: C0115: Missing class docstring (missing-class-docstring)
test2.py:7:0: C0115: Missing class docstring (missing-class-docstring)
test2.py:13:0: C0116: Missing function or method docstring (missing-function-docstring)
test2.py:13:0: C0104: Disallowed name "foo" (disallowed-name)
test2.py:20:23: E1101: Instance of 'Base' has no 'child_field' member (no-member)
test2.py:13:0: R1710: Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements)
test2.py:25:0: C0116: Missing function or method docstring (missing-function-docstring)
test2.py:25:0: C0104: Disallowed name "bar" (disallowed-name)

------------------------------------------------------------------
Your code has been rated at 3.16/10 (previous run: 2.67/10, +0.49)

Expected behavior

Inferred type of variable ex on lines 19-20 is Child; no warning is emitted on line 20.

Pylint version

pylint 3.0.2
astroid 3.0.1
Python 3.11.2 (tags/v3.11.2:878ead1, Feb  7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)]

OS / Environment

Windows 10

Metadata

Metadata

Assignees

No one assigned

    Labels

    AstroidRelated to astroidFalse Positive 🦟A message is emitted but nothing is wrong with the codeMatch caseNeeds astroid updateNeeds an astroid update (probably a release too) before being mergable

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions