True lies and falsy values in Python and Javascript

In Python and Javascript programming you can compare different values against true or false even if they are not boolean values as is.  By knowing this, writing some code paths become simpler.

The most used example is None in Python (None would be null in other programming languages):

>>> spoon = False
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon

>>> spoon = None
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon

None is not same as False in Python, but if truth comparison treats it is as were.

In Python, the values which have falsy comparison include, but are not excluded to

  • empty string
  • empty lists and tuples
  • number zero

Further examples:

>>> spoon = ()
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon
>>> spoon = []
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon
>>> spoon = ""
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon

So it actually doesn’t make then sense to test both for None or empty string as you could get away with one condition.

>>> banana = ""
>>> print "I am banana" if (banana != '' and banana is not None) else "Muttia miehelle"
Muttia miehelle

The above if could have been written just as if banana.

As a word of warning, some framework classes may implement their own __eq__() and related method causing surprising when doing “if something:” and then expecting it to check for None values only. In these cases, you need to explicitly use is operator to compare against None. is tests if the values point to the same object (a reference comparison) and there exists only one None object in Python. Example:

>>> banana = ""
>>> print "I am banana" if (banana is not None) else \
    "Should not be reached as we explicitly used is comparator"
I am banana

Sometimes you need to process the values which can be string or None, depending on what your favorite form framework have spit out. Then you can use the following or comparison trick to shorten the code not to have extra if: If the left side of or evaluates to false like value (None) then the right side is used. We can use this to force falsy values to be empty string always. Example:

>>> string_like_value = None
>>> print string_like_value.strip()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'strip'

>>> string_like_value = None
>>> print (string_like_value or "").strip()

>>> string_like_value = "  foobar  "
>>> print (string_like_value or "").strip()
foobar

Unlike Python, Javascript does not raise error when accessing a missing attribute on an object. Instead, accessing an undefined variable gives you back undefined value which equals to false in boolean comparisons.

undefined values result to hilarious debugging sessions as a mistyped variable does not cause error or stack trace where it is being accessed, but somewhere deeper in the code not related to the place of an actual error. You can mitigate the risk of this by spreading asserts all around your code to check possible bad function arguments in your own code.

However, undefined as a perverted language feature can be exploited for creating a configurator design pattern (not sure if this pattern has any better name?) as shown below. In Javascript, this pattern is commonly used to give configuration parameters to library functions. Several values are read from layered configuration objects and the highest set value is used – falling back to the defaults if no value is given.

var globalConfig = { x : 3 }
var foobar = function(config) { 
    this.x = config.x || globalConfig.x || "some default value if even global config is missing"; 
    console.log(this.x); 
}
// No x given, so function above should use 
// the default x value from globalConfig
foobar({y:4});
3

Javascript also features === and !== comparisons which equals to Python is comparison. This can be used to check against undefined explicitly.

>> foobar = "";
>> if(!foobar) console.log("Has no foo");
Has no foo

>> foobar = undefined;
>> if(!foobar) console.log("Has no foo");
Has no foo

>> foobar = "";
>> if(foobar !== undefined) console.log("Has no undefined foo");
Has no undefined foo

To make things even more hilarious, undefined could be redefined before ECMAScript 5…

Please share your favorite boolean like comparison trick 🙂

Then, True Lies (1994):

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

4 thoughts on “True lies and falsy values in Python and Javascript

  1. In my experience, doing “if foo” instead of “if foo is not None” is a very common source of bugs in Python. If, at the time of writing, you have in mind “if foo is not None”, you should always write that, and not take the shortcut “if foo”.

    Also, === and !== in javascript do not correspond to “is” and “is not” in Python. Those operators in javascript mean “equal and of the same time”, while “is” in Python has to do with object identity.

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators
    http://docs.python.org/reference/expressions.html#not-in

  2. i also like boolean statements like:

    >>> spoon = None
    >>> print spoon is not None and “Porridge time” or “There is no spoon”
    There is no spoon

  3. Pingback: JavaScript Basics | Beyond the Comfort Zone

Leave a Reply

Your email address will not be published. Required fields are marked *