Error in mypy when using any() or all() to check for None in a iterable
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Mypy raises errors indicating the absence of attributes for objects of type "None" when using any() or all().
To Reproduce
from dataclasses import dataclass
def get_hobby_description(hobby: str) -> ...: ...
def get_best_friend_info(best_friend: str) -> ...: ...
@dataclass
class Person:
name: str
age: int
hobby: str | None = None
best_friend: str | None = None
person = Person(name="name", age=0, hobby=None, best_friend=None)
if not all((person.hobby, person.best_friend)):
raise ValueError
if not any((person.hobby, person.best_friend)):
raise ValueError
hobby_description = get_hobby_description(person.hobby)
best_friend_info = get_best_friend_info(person.best_friend)
Expected Behavior
The code should be recognized as correct since it checks for the absence of None among the variables person.hobby and person.best_friend.
Actual Behavior
Mypy raises errors indicating the absence of attributes for objects of type "None" when using any() or all().
error: Argument 1 to "get_hobby_description" has incompatible type "str | None"; expected "str" [arg-type]
error: Argument 1 to "get_best_friend_info" has incompatible type "str | None"; expected "str" [arg-type]
Your Environment
- Mypy version used: mypy 1.10.0 (compiled: yes)
- Mypy command-line flags: No
- Mypy configuration options from
mypy.ini(and other config files): No - Python version used: 3.12.2
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
No source file or test is named. Start by running the provided dataclass reproducer with mypy 1.10.0 and inspect how any() and all() affect narrowing of optional attributes. Done means the reported behavior is resolved or its intended semantics are documented and covered by a regression test.
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