python / python/mypy

Parameterized protocol structure ignored as argument

Open
#14,798 1 comment 0 reactions 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

Parameterized protocols seem to be largely or totally ignored when specified as argument types. Simple example:

from typing import Protocol, TypeVar

T = TypeVar("T")
T_co = TypeVar("T_co", covariant=True)


class Proto(Protocol[T_co]):
    def __call__(self, *, a: str) -> T_co:
        ...


class InvalidClass:
    def __init__(self, *, a: int) -> None:
        ...


def test(b: Proto[T]) -> T:
    return b(a="0")
    

test(InvalidClass)  # <-- should fail type checking

InvalidClass is accepted here even though it does not conform to the protocol. Here's a more detailed playground gist.

As demonstrated in the gist, the issue does not reproduce when a function is provided, only with a class. It also does not manifest with assignment, only with arguments. However, assigning with the parameter set to Any also produces an unexpected result, which might somehow be related.

  • Mypy version used: 1.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.11

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 minimal example with mypy 1.0 on Python 3.11, then compare it with the linked playground gist and its strict flags. The fix is complete when mypy rejects test(InvalidClass) for failing to conform to Proto, while preserving the reported behavior for functions and assignments.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.