The Python Oracle

Python explicit condition checking compared to implicit

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping

--

Chapters
00:00 Python Explicit Condition Checking Compared To Implicit
00:45 Accepted Answer Score 2
02:19 Answer 2 Score 1
02:53 Answer 3 Score 1
03:25 Thank you

--

Full question
https://stackoverflow.com/questions/3290...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #codingstyle

#avk47



ACCEPTED ANSWER

Score 2


There's a couple things going on here. First off, let's tackle "truthy" values. In python, most object are "truthy", meaning they evaluate to true in a statement such as if thing: do other_thing.

There are actually quite few objects that are "falsey", as documented here (I know, Python 2.4 docs... don't worry, it's still valid).

So why does this matter? It lets you write cleaner code! If you are expecting whether something is or isn't, there is no need to check exactly what it is. It's an empty list? Fine, that's nothing. Empty string? Still nothing. Oh, I got back a dictionary with one key:value pair? That's something! This is where "Pythonic" comes in - it's a convention settled upon by the community. Everyone decided it made sense and looked nicer, so it's stuck.

This allows you great flexibility in your code. You don't have to check the type of an object, you just need to know if it contains data or not.

You should only ever check == if you really really care that an object is equal to another object.

Examples:

def check_shopping_list(shopping_list):
    if shopping_list:  # No need to check len(), just that it has contents
        for item in shopping_list:
            pass
    else:
        raise EmptyShoppingList("You should really add SPAM to your list")


def validate_input(input):
    if not input:  # catches empty inputs
        raise MissingInput("Please try again")
    else:
        print("Validated!")


def read_file(file_name):
    if os.path.exists(file_name):  # returns True/False, but we don't have to explicitly state that
        with open(file_name) as doc:
            pass
    else:
        print("That file doesn't exist, do you want to create it?")



ANSWER 2

Score 1


In above code variable 'a' can be any data type int, string, list. So the meaning of first version is like if it is integer and if it is not zero then it will go in if loop, if it string and not empty it will go in if loop etc. Second version is more likely taken from traditional languages like C,C++ etc. where the variable is more likely Boolean variable that's why it is compared with 'true'.

So most of the people working with python will like first version, since it is more generic.




ANSWER 3

Score 1


Another tenet of Pythonic code is, "Simple is better than complex."

The whole point of an if statement is to check if an expression is truthy according to the rules of that language. (Admittedly, Python's rules for truthiness are more complex than those for most other languages.) If you know that, for the purpose of your if clause, all possible truthy values of your expression are distinct from all possible falsey values, then you're already as explicit as you need to be.