Does this Python expression make sense?
Asked Answered
A

4

5

I found this kind of expression several times in a python program:

if variable is not None:
    dothings(variable)

It seems strange to me, and I think that it has no more sense than:

if variable:
    dothings(variable)

Maybe I don't know Python enough, and the expression is explained somewhere?

Astigmatic answered 29/11, 2012 at 15:6 Comment(0)
G
14

variable could be 0, or False, or [], or (); be 'falsy' in other words, and then the if statement would be skipped.

See Truth testing for more detail on what is considered false in a boolean context.

In short, testing if variable is not None allows variable to be anything else, including values that would otherwise be considered False in a boolean context.

Gonion answered 29/11, 2012 at 15:7 Comment(2)
So, .... "A is not B" is different that "A is not B" and Python applies the former. Isn't it?Astigmatic
is not is the inverse of is, yes. See docs.python.org/2/reference/expressions.html#not-in. You could also say not A is B.Gonion
M
5

Some values are falsy, but are not None. You may still want to dothings() to those values.

Here are the things that are falsy in Python 2. (You may want to change the '2' in the URL to a '3' to get the values for Python 3, but it didn't change much.)

Madore answered 29/11, 2012 at 15:7 Comment(0)
A
1

E.g.

i = 0

if i is not None:
    print i    # prints i

if i:
    print i    # prints nothing
Archaic answered 29/11, 2012 at 15:8 Comment(0)
B
0

In the google voice python implementation I came across this as well, their use was during a function call. The parameters are defaulted to "None" and then when the function is called they can check if the values are changed or the default. I.E.

def login (user=None, password=None)
  if user is None:
     user = input('Please enter your username');
  ...
  return <something>;

called by

login()

OR

login(user='cool_dude')

OR

any combination of user/password you wish.

Additionally your "update" of the logic implies that variable == true or false. That is not correct for all cases (it may work in some cases but I'm throwing them out, since it's not a general case). What you are testing by using the "NONE" logic is whether the variable contains anything besides NONE. Similar to what I was saying above, all the "login function" was doing was determining if the user passed anything, not whether the value was valid, true, etc.

Brainard answered 29/11, 2012 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.