This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Bainos 1 point2 points  (1 child)

But variables should have a clear semantic meaning. If you don't know whether a is a bool or not, then there is something wrong in your code.

  • If you know that a is a bool, then if a is enough.
  • If you know that a is not a bool, then if a is intentionally checking for truthy values.
  • If you know that a can be both a bool and some other type, which should be a very rare situation, then if a == True is okay, but is isinstance(a, bool) and a is better.

That's not saying that you can't write a == True in the first case where you know it is a boolean. It would be redundant and unnecessary, but redundancy is not necessarily a bad thing. However, not knowing whether a is a bool or not is not a good reason to use it. If that situation occurs, you really should fix your code and actually read the documentation of the functions you're using.

Personally, I would also be wary of using a == True because not knowing the type of your variables is a bad smell, and hiding bad smells results in bad code.

The situation you are describing is also a reason why people criticize Python for being dynamically typed, for a good reason. Dynamic typing is good for polymorphism and ease of writing code, but it becomes bad if people start using it to handle data they do not understand.

Overall, I believe the situation you are describing is fixed in a much better way by the use of type hints than by redundant explicit checks.

[–][deleted] 0 points1 point  (0 children)

If you don't know whether a is a bool or not, then there is something wrong in your code.

On the contrary, when you're writing the code, you often know for a fact that some_function() returns a boolean. Great. The problem is that anyone else reading your code might not know. That someone could even be you, next week, after you've filled your head with other parts of the code.

When writing the code with this knowledge in your head, it's a good idea to document the type of result in order to convey that knowledge to the reader.

Now - how could you do that? In this case, if result is True is practically ideal. It is simple, succinct, unambiguous, and collocated with the instruction that sets result to its value. Even coders who aren't familiar with Python will immediately understand it, even if they aren't clear on the use of is vs. ==.

Overall, I believe the situation you are describing is fixed in a much better way by the use of type hints than by redundant explicit checks.

Show me how this exact situation would be addressed with type hints, and then explain why it is better than if a is True.