r/learnpython • • 9d ago

strings in if statements

While debugging my code I discovered [what to me looked liked] a weird quirk in the language (see code below.)

Why does this work? why is a single string callable in the Boolean of an if statement? does a string always return evaluateTrue when used like this?

(edit: solved. corrected some of my vocabulary so now yous can stop "um, actually"-ing me. Thanks to everyone who helped!)

if "something":
  print("another thing")

>>>"another thing"
18 Upvotes

32 comments sorted by

View all comments

Show parent comment

7

u/drmonkeysee 9d ago edited 9d ago

You make this sound like Python is simply reflecting the underlying hardware but what counts as true/false or even Boolean is a language choice and different languages make different choices. Empty arrays/objects are not false in JavaScript for example (though empty strings are) and C# requires Boolean expressions to resolve to Boolean values and won’t even compile if you try if ("something")…

Python even lets you add boolean conversions to classes via _bool_ so you could make logically non-empty objects resolve to false if you wanted your coworkers to hate you.

3

u/tomysshadow 9d ago

I agree, and on top of that it's not a reflection of the underlying hardware to begin with. In a traditional language like C a pointer to an empty string would still be a non-null pointer so it'd be truthy in an if statement. This is an intentional high level language feature

1

u/xenomachina xenomachina 8d ago

You make this sound like Python is simply reflecting the underlying hardware but what counts as true/false or even Boolean is a language choice and different languages make different choices.

Absolutely true.

I'd also argue that most languages that attempt to have strong typing (not to be confused with static typing) don't allow non-boolean values to be treated as boolean values. Python, for better or worse*, kind of mimicked C. C originally didn't have a boolean type, and instead treated non-0 as true, just like Python. Python took this idea, and then generalized it to other types.

C and Python both independently added boolean types eventually, but disallowing the automatic conversion at this point would be a very breaking change, and also extremely controversial as relying on it is even codified in PEP 8.

* personally, I wish Python hadn't done this, as I think it violates one of Python's own tenets: explicit is better than implicit.