python / python/mypy

Common type in container is determined using constructor args

Open
#11,659 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

To Reproduce

from typing import Type, List


class NonLiskovChild(Exception):
    """Does not match Exception.__init__() signature"""
    def __init__(self, _some_other_arg: object) -> None:
        super().__init__()


types1 = [TypeError, ValueError]
reveal_type(types1)
# Revealed type is 'builtins.list[def (*args: builtins.object) -> builtins.Exception]'

types2 = [TypeError, NonLiskovChild]
reveal_type(types2)
# Revealed type is 'builtins.list[builtins.type*]'

# When explicitly setting the type, mypy accepts NonLiskovChild as an Exception subtype:
types3: List[Type[Exception]] = [TypeError, NonLiskovChild]
reveal_type(types3)
# Revealed type is 'builtins.list[Type[builtins.Exception]]'

Expected Behavior

The lowest common type should be determined by inheritance, not with __init__() signature matching.

Otherwise stdlib classes like CalledProcessError do not work correctly, e.g. in this example:

import pytest
from subprocess import CalledProcessError

with pytest.raises((TypeError, CalledProcessError)) as exc_info:
    pass
# error: Need type annotation for "exc_info"
# error: Argument 1 to "raises" has incompatible type "Tuple[Type[TypeError], Type[CalledProcessError]]"; expected "Union[Type[<nothing>], Tuple[Type[<nothing>], ...]]"

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.8.10
  • Operating system and version: Windows 10

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the two reveal_type examples and the pytest.raises case from the issue. Trace how the container's common type is inferred from the class constructors, then verify that the reported Exception subclasses produce the expected inferred types and no incompatible-argument errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.