Skip to content

Possible truthy-bool false positive with := #15685

Closed

Description

@sobolevn

Consider this code with truthy-bool:

class A:
    def method(self) -> bool:
        return True  # whatever


if (a := A()) and a.method():
    print(a)

It will output:

» mypy ex.py --enable-error-code=truthy-bool
ex.py:6: error: "ex.a" has type "A" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]
ex.py:6: error: "ex.A" returns "A" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]

Two questions:

  1. Why two errors?
  2. Maybe we should skip this rule completely for (:=) and ..., because a is not really the main thing we check here?

CC @ikonst

Activity

  1. changed the title [-]Possible `thruthy-bool` false positive with `:=`[/-] [+]Possible `truthy-bool` false positive with `:=`[/+] on Jul 15, 2023
  2. AlexWaygood commented on Jul 15, 2023

    @AlexWaygood
    Member

    I think it would probably be better to emit one error rather than two here. But I don't think I agree that it's a false positive. The first side of the left operand will always evaluate to True, so you could write the snippet more simply as:

    class A:
        def method(self) -> bool:
            return True  # whatever
    
    
    if (a := A()).method():
        print(a)
  3. ikonst commented on Jul 15, 2023

    @ikonst
    Contributor

    Agree with (1), need to look into it.

    Don't see compelling evidence to special-case (2). This code uses and creatively as a statement separator (since lhs is always true), and I'm not convinced this is idiomatic or common (just browsed over examples in PEP-572 but I might've missed something).

  4. self-assigned this
    on Aug 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugmypy got something wrongtopic-pep-572PEP 572 (walrus operator)

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions