Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"None not in" vs "not None in"

Unless I'm crazy if None not in x and if not None in x are equivalent. Is there a preferred version? I guess None not in is more english-y and therefore more pythonic, but not None in is more like other language syntax. Is there a preferred version?

like image 490
Falmarri Avatar asked Aug 30 '10 21:08

Falmarri


People also ask

What does not None mean?

None is the pronoun form of no. None means 'not one' or 'not any'.

Is None and None same in Python?

None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

Why use is None instead of == None?

None is a singleton object (there only ever exists one None ). is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.

Should I use is not None Python?

You should use the is not operator when you need to check if a variable doesn't store a None value. When we use is or is not , we check for the object's identity. The pep 8 style guide mentions that comparison to singletons like None should always be done with is or is not , and never the equality operators.


2 Answers

They compile to the same bytecode, so yes they are equivalent.

>>> import dis
>>> dis.dis(lambda: None not in x)
  1           0 LOAD_CONST               0 (None)
              3 LOAD_GLOBAL              1 (x)
              6 COMPARE_OP               7 (not in)
              9 RETURN_VALUE
>>> dis.dis(lambda: not None in x)
  1           0 LOAD_CONST               0 (None)
              3 LOAD_GLOBAL              1 (x)
              6 COMPARE_OP               7 (not in)
              9 RETURN_VALUE

The documentation also makes it clear that the two are equivalent:

x not in s returns the negation of x in s.

As you mention None not in x is more natural English so I prefer to use this.

If you write not y in x it might be unclear whether you meant not (y in x) or (not y) in x. There is no ambiguity if you use not in.

like image 157
Mark Byers Avatar answered Sep 19 '22 10:09

Mark Byers


The expression

not (None in x) 

(parens added for clarity) is an ordinary boolean negation. However,

None not in x

is special syntax added for more readable code (there's no possibility here, nor does it make sense, to use and, or, etc in front of the in). If this special case was added, use it.

Same applies to

foo is not None

vs.

not foo is None

I find the "is not" much clearer to read. As an additional bonus, if the expression is part of a larger boolean expression, the scope of the not is immediately clear.

like image 38
Ivo van der Wijk Avatar answered Sep 21 '22 10:09

Ivo van der Wijk