Skip to content

Error in mypy when using any() or all() to check for None in a iterable #17218

@kingco6ra

Description

@kingco6ra

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions