Type not narrowed on `isinstance(obj, Callable)` check
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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