3

In Python I am very used to using the logical operators and and or and was under the impression that they'd simply get evaluated with the left and right values and replaced with True or False at runtime.

I recently discovered that this is not the case. Consider:

>>> False or 10
10

I see the use case. Here if you have a function that returns a value or False on failure the above allows you to have a default fallback value. But with and:

>>> True and re.match("s", "s")
<_sre.SRE_Match object at 0x19f9098>

This puzzles me... It seems that the last operand of an and evaluation where both operands evaluate to True is always returned which makes sense in that it's the last one to run but I don't see why this is preferable to just having a bool.

Why does python do this? Is there a use case for this that I'm not seeing? In situations where you know you want a bool is it a good idea to convert these values? eg:

>>> bool(True and re.match("s", "s"))
True
nettux
  • 5,270
  • 2
  • 23
  • 33

1 Answers1

-1

In Python doc's words:

This is sometimes useful, e.g., if s is a string that should be replaced by a default value

Boolean operations doc.

scagnetti
  • 1,435
  • 3
  • 20
  • 38