Wrong truthy-function with a constrained TypeVar
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
from typing import Callable, Collection, TypeVar
T = TypeVar("T", Callable[[], int], Collection[int])
def test(x: T) -> bool:
if not x:
return False
return True
https://mypy-play.net/?mypy=latest&python=3.11&gist=ab304abd8323804aba46fb9227d6fbb2
Expected Behavior
The if condition is used for both functions and collections. It's used to filter out empty collections. This should type check without errors.
Actual Behavior
mypy returns an error which assumes that x can only be a function:
truthy_function.py:6: error: Function "x" could always be true in boolean context [truthy-function]
Your Environment
- Mypy version used: 1.4.1 (compiled: yes)
- Python version used: 3.10.11
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
Reproduce the example in the linked mypy-play configuration with Python 3.11 and inspect the [truthy-function] diagnostic reported at truthy_function.py:6. Trace the handling of constrained TypeVar values in boolean contexts, then verify that the Callable/Collection example type-checks without the erroneous warning.
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
- 35/100