python / python/mypy

Disallow type(x) if x has a protocol type

Open
#16,919 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Modules can implement protocols, so type(x) is not necessarily a type object if x has a protocol type.

from typing import Protocol

class P(Protocol):
    def f(self) -> None: ...


def f(p: P) -> None:
    reveal_type(type(p))  # type[P] (incorrect!)

It's probably best to to generate an error if type is called on an object with a protocol type, as suggested by @hauntsaninja in https://github.com/python/mypy/issues/16890#issuecomment-1937529825.

See #16890 for more context.

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 with the type(p) call in the Protocol example and read #16890 for the stated context. Verify that protocol-typed values no longer produce the incorrect type[P] result and that the intended error is covered by the relevant tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.