python / python/mypy

Type not narrowed on `isinstance(obj, Callable)` check

Open
#11,071 6 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I received this bug report from a pyright user: https://github.com/microsoft/pyright/issues/2274. Mypy exhibits the same behavior, so I'm wondering whether it's a bug or the intended behavior.

In this code sample, mypy (and pyright) do not currently narrow the type of obj based on the isinstance(obj, Callable) conditional check.

from typing import Callable, Union

def some_func(obj: Union[Callable, int]):
    if isinstance(obj, Callable):
        reveal_type(obj) # Type of "obj" is "(*args: Unknown, **kwargs: Unknown) -> Unknown | int"
    else:
        reveal_type(obj) # Type of "obj" is "(*args: Unknown, **kwargs: Unknown) -> Unknown | int"

I'm wondering if there's a reason why mypy does not perform type narrowing in this case. Is there a type safety reason? Is callable() the preferred way to check for callables?

I've searched the issue database, and it doesn't appear to be an issue that anyone has previously reported.

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 running the Python reproducer with mypy and checking the revealed types for both branches. Trace the existing isinstance and Callable narrowing behavior, including any related tests or documentation. Done means establishing whether this behavior is intentional and, if it is a bug, defining a tested narrowing result.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.