Another Python keyword. This time it’s a widely misunderstood and high-profile one:
None
None is not what your typical English-speaking, non-coder might expect. That is, None is not just another way of expressing zero (or zip, zilch, nada, bubkis, or diddly–squat, for that matter). In fact, None is not equal to zero at all. If we assert that None is equal to zero, Python will set us straight, as follows:
>>> None == 0 False
None is also not equal to an empty list:
>>> None == [] False
As we mentioned when discussing del, you don’t utterly eradicate something when you assign it to None. Rather, None indicates that something doesn’t have a specific value even though it exists as an object. It literally becomes a “Nonetype,” which is a unique ghost in the Python universe.
>>> x = None >>> x >>> type(x) <class 'NoneType'>
So, what the heck does one do with a NoneType, anyway?
In a sense, your function will return None as a sort of last resort or shrug of the shoulders. It says, “Yeah, this is all I got and it’s pretty much bubkis” and then shoots out a None. For example, try to call and print the following function:
def return_not_nothing(): big = "a big fat bowl" nearly_null = " of not nothing" squat = big + nearly_null return squat
print(return_not_nothing())
If we run this code, it produces “a big fat bowl of not nothing”
Now, run it again without officially returning anything (that is, without the last line of the function).
def return_not_nothing(): big = "a big fat bowl" nearly_null = " of not nothing" squat = big + nearly_null
print(return_not_nothing())
This time the code produces None.
Why? Because even though the code is doing something, it doesn’t actually produce a value. In lieu of a value, it automatically returns None.
Sometimes a function will usually return a value but occasionally return None. The function below, for example, will return a None about one out of 10 times. That’s because we haven’t told it to return anything in particular if random.randint selects a six.
import random
def re_turn_squat (): big = "big fat bowl" null = " of not nothing" if random.randint(1,10) != 6: squat = big + null return squat
print(re_turn_squat())
So, is None the same as null in some other computer languages? Well, it can be a close cousin, but None is not the lack of an object (as a null reference can apparently be) but, as we mentioned, a kind of unique object. Using my best Zen-like thinking, I tend to think of it as the sound of one computer shrugging.
For a deeper look at None, I recommend the following:
Featured image is the enso, a symbol of Zen Buddhism, by Zenwhat