1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Does mypy not consider "bool(object) == True"?

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    If Python classes do not define __bool__ or __len__, bool(<class object>) defaults to True.

    However, mypy (tested with: v1.15.0) doesn't seem to consider this.

    class A:
    def __init__(self) -> None:
    self._value = 42

    def foobar(self) -> int:
    return self._value


    def foobar(a: A | None) -> int | None:
    # case: `a is None` ⇒ returns `None`
    # case: `a is not None` ⇒ returns `42`
    # however: mypy complains...
    # `Incompatible return value type (got A | int | None), expected "int | None"`
    return a and a.foobar()


    To my understanding, the expression a and a.foobar() can only evaluate to type A if a is not None and bool(a) == False, which cannot happen. My conclusion is that mypy doesn't consider that a is not None ⇒ bool(a) == True.

    Am I right that mypy simply fails on this? Is there any convenient workaround to write optional_obj and optional_obj.attribute in a mypy-compatible way?

    Continue reading...

Compartilhe esta Página