Python 'If not' syntax

PythonPython 2.7

Python Problem Overview


I'm a bit confused about how/why so many python developers use if not in their conditional statements.

for example, lets say we had a function,

def foo(bar = None):
    if not bar:
        bar = 2

But why go about this way? I mean, wouldn't doing if bar != None or if bar is not Nonebe more explicit? What does if not try to say?

Python Solutions


Solution 1 - Python

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdgarAroutView Question on Stackoverflow
Solution 1 - Pythonuser395760View Answer on Stackoverflow