Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Idea: warn if an object without a "significant" boolean representation is used in a boolean context #8646

Closed
brianmaissy opened this issue Apr 7, 2020 · 3 comments

Comments

@brianmaissy
Copy link

This is a bit of a long shot, because this isn't really a type error per se. But consider the following:

numbers: List[int] = []
my_generator: Iterable = (i for i in numbers)
if not my_generator:
    print("empty")

Obviously this will not print "empty", because a is a generator, which is always truthy. However, 99.9% of the times this is not what the user intended, and it would be great if a tool could identify it and warn about it, and mypy seems well-placed to be able to do it.

Beyond the fact that this isn't really a type "error", there are some more complications. For example, how to more generally define what objects don't have a "significant" boolean representation. One could argue that this is just as much a "mistake" as the example with the generator:

class A:
    pass

a: A = A()
if not a:
    print("empty")

As well as the question of what's considered "using something in a boolean context". Should calling bool() on a generator be the same as using it in the conditional expression of an if or while?

So I'm not at all sure this is a feasible or reasonable suggestion, but I didn't find any mention if it in past issues, so thought it was worth bringing up for discussion.

@JukkaL
Copy link
Collaborator

JukkaL commented Apr 9, 2020

I've encountered similar issues myself, though I can't remember if there has been any online discussion about these. Stricter boolean checks would at least be nice as an opt-in check.

@hauntsaninja
Copy link
Collaborator

#10666 will add an opt-in check for this.

@Akuli
Copy link
Contributor

Akuli commented Oct 25, 2021

Can this be closed, now that #10666 is merged?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants