1458

How do I refer to the null object in Python?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Lizard
  • 43,732
  • 39
  • 106
  • 167

9 Answers9

1923

In Python, the 'null' object is the singleton None.

To check if something is None, use the is identity operator:

if foo is None:
    ...
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Ben James
  • 121,135
  • 26
  • 193
  • 155
  • 146
    And the reason for choosing `egg is None` over `egg == None`: The latter can be overloaded, and is likely to break when comparing valid object with None (depends on how it's implemented, but you don't expect everyone to take comparisions with None into account, do you?), while `is` always works the same. –  Jul 20 '10 at 12:25
  • 105
    why didnt the python designers just choose "null". Just have to be different don't you ! ;) – Vidar Mar 26 '13 at 09:44
  • 41
    @Vidar 'None' isn't a lack of an object (as 'null' is, a null reference), it's an actual object. You'll never get a 'None' object passing for an object that's of a type of anything other than 'NoneType'. It's also not a language concept.. It's not built in to Python the language, it's part of Python's standard library. None !== (ahem) Null – Rushyo Jun 12 '13 at 12:17
  • 1
    @Rushyo: so there is no way of having a null reference in python? – naught101 Sep 02 '14 at 11:18
  • 13
    @naught101 It would serve no purpose; as there is no concept of pointers. If you are using the ctypes library, None will be used as a synonym for address zero but there's still no language concept of a 'null reference'. In Python, you always left referencing some kind of object, even if that object is None. I suspect this greatly simplifies the language. – Rushyo Sep 02 '14 at 13:26
  • 7
    great presentation explaining the 'billion dollar mistake' that is the null ref: http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare. Other options instead of null are Options, or Maybe (custom) types. – Michahell Apr 08 '15 at 23:56
  • 5
    And for completeness, the inverse of this is `if foo is not None:`. – devios1 Jan 04 '17 at 22:56
  • Would `if not foo:` not suffice? – ivvi Oct 03 '18 at 15:13
  • @seron `if not foo:` equals `if foo is not True`, has nothing to do with `None`. – deadvoid Oct 05 '18 at 07:28
  • Why does the String's `find()` method return -1 when it can't find a substring given `None` is an available option? – ScottyBlades Oct 06 '19 at 08:12
245

None, Python's null?

There's no null in Python; instead there's None. As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.

>>> foo is None
True
>>> foo = 'bar'
>>> foo is None
False

The basics

There is and can only be one None

None is the sole instance of the class NoneType and any further attempts at instantiating that class will return the same object, which makes None a singleton. Newcomers to Python often see error messages that mention NoneType and wonder what it is. It's my personal opinion that these messages could simply just mention None by name because, as we'll see shortly, None leaves little room to ambiguity. So if you see some TypeError message that mentions that NoneType can't do this or can't do that, just know that it's simply the one None that was being used in a way that it can't.

Also, None is a built-in constant. As soon as you start Python, it's available to use from everywhere, whether in module, class, or function. NoneType by contrast is not, you'd need to get a reference to it first by querying None for its class.

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

You can check None's uniqueness with Python's identity function id(). It returns the unique number assigned to an object, each object has one. If the id of two variables is the same, then they point in fact to the same object.

>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000

None cannot be overwritten

In much older versions of Python (before 2.4) it was possible to reassign None, but not any more. Not even as a class attribute or in the confines of a function.

# In Python 2.7
>>> class SomeClass(object):
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: cannot assign to None
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to None

# In Python 3.5
>>> class SomeClass:
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: invalid syntax
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to keyword

It's therefore safe to assume that all None references are the same. There isn't any "custom" None.

To test for None use the is operator

When writing code you might be tempted to test for Noneness like this:

if value==None:
    pass

Or to test for falsehood like this

if not value:
    pass

You need to understand the implications and why it's often a good idea to be explicit.

Case 1: testing if a value is None

Why do

value is None

rather than

value==None

?

The first is equivalent to:

id(value)==id(None)

Whereas the expression value==None is in fact applied like this

value.__eq__(None)

If the value really is None then you'll get what you expected.

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True

In most common cases the outcome will be the same, but the __eq__() method opens a door that voids any guarantee of accuracy, since it can be overridden in a class to provide special behavior.

Consider this class.

>>> class Empty(object):
...     def __eq__(self, other):
...         return not other

So you try it on None and it works

>>> empty = Empty()
>>> empty==None
True

But then it also works on the empty string

>>> empty==''
True

And yet

>>> ''==None
False
>>> empty is None
False

Case 2: Using None as a boolean

The following two tests

if value:
    # Do something

if not value:
    # Do something

are in fact evaluated as

if bool(value):
    # Do something

if not bool(value):
    # Do something

None is a "falsey", meaning that if cast to a boolean it will return False and if applied the not operator it will return True. Note however that it's not a property unique to None. In addition to False itself, the property is shared by empty lists, tuples, sets, dicts, strings, as well as 0, and all objects from classes that implement the __bool__() magic method to return False.

>>> bool(None)
False
>>> not None
True

>>> bool([])
False
>>> not []
True

>>> class MyFalsey(object):
...     def __bool__(self):
...         return False
>>> f = MyFalsey()
>>> bool(f)
False
>>> not f
True

So when testing for variables in the following way, be extra aware of what you're including or excluding from the test:

def some_function(value=None):
    if not value:
        value = init_value()

In the above, did you mean to call init_value() when the value is set specifically to None, or did you mean that a value set to 0, or the empty string, or an empty list should also trigger the initialization? Like I said, be mindful. As it's often the case, in Python explicit is better than implicit.

None in practice

None used as a signal value

None has a special status in Python. It's a favorite baseline value because many algorithms treat it as an exceptional value. In such scenarios it can be used as a flag to signal that a condition requires some special handling (such as the setting of a default value).

You can assign None to the keyword arguments of a function and then explicitly test for it.

def my_function(value, param=None):
    if param is None:
        # Do something outrageous!

You can return it as the default when trying to get to an object's attribute and then explicitly test for it before doing something special.

value = getattr(some_obj, 'some_attribute', None)
if value is None:
    # do something spectacular!

By default a dictionary's get() method returns None when trying to access a non-existing key:

>>> some_dict = {}
>>> value = some_dict.get('foo')
>>> value is None
True

If you were to try to access it by using the subscript notation a KeyError would be raised

>>> value = some_dict['foo']
KeyError: 'foo'

Likewise if you attempt to pop a non-existing item

>>> value = some_dict.pop('foo')
KeyError: 'foo'

which you can suppress with a default value that is usually set to None

value = some_dict.pop('foo', None)
if value is None:
    # Booom!

None used as both a flag and valid value

The above described uses of None apply when it is not considered a valid value, but more like a signal to do something special. There are situations however where it sometimes matters to know where None came from because even though it's used as a signal it could also be part of the data.

When you query an object for its attribute with getattr(some_obj, 'attribute_name', None) getting back None doesn't tell you if the attribute you were trying to access was set to None or if it was altogether absent from the object. The same situation when accessing a key from a dictionary, like some_dict.get('some_key'), you don't know if some_dict['some_key'] is missing or if it's just set to None. If you need that information, the usual way to handle this is to directly attempt accessing the attribute or key from within a try/except construct:

try:
    # Equivalent to getattr() without specifying a default
    # value = getattr(some_obj, 'some_attribute')
    value = some_obj.some_attribute
    # Now you handle `None` the data here
    if value is None:
        # Do something here because the attribute was set to None
except AttributeError:
    # We're now handling the exceptional situation from here.
    # We could assign None as a default value if required.
    value = None
    # In addition, since we now know that some_obj doesn't have the
    # attribute 'some_attribute' we could do something about that.
    log_something(some_obj)

Similarly with dict:

try:
    value = some_dict['some_key']
    if value is None:
        # Do something here because 'some_key' is set to None
except KeyError:
    # Set a default
    value = None
    # And do something because 'some_key' was missing
    # from the dict.
    log_something(some_dict)

The above two examples show how to handle object and dictionary cases. What about functions? The same thing, but we use the double asterisks keyword argument to that end:

def my_function(**kwargs):
    try:
        value = kwargs['some_key']
        if value is None:
            # Do something because 'some_key' is explicitly
            # set to None
    except KeyError:
        # We assign the default
        value = None
        # And since it's not coming from the caller.
        log_something('did not receive "some_key"')

None used only as a valid value

If you find that your code is littered with the above try/except pattern simply to differentiate between None flags and None data, then just use another test value. There's a pattern where a value that falls outside the set of valid values is inserted as part of the data in a data structure and is used to control and test special conditions (e.g. boundaries, state, etc.). Such a value is called a sentinel and it can be used the way None is used as a signal. It's trivial to create a sentinel in Python.

undefined = object()

The undefined object above is unique and doesn't do much of anything that might be of interest to a program, it's thus an excellent replacement for None as a flag. Some caveats apply, more about that after the code.

With function

def my_function(value, param1=undefined, param2=undefined):
    if param1 is undefined:
        # We know nothing was passed to it, not even None
        log_something('param1 was missing')
        param1 = None


    if param2 is undefined:
        # We got nothing here either
        log_something('param2 was missing')
        param2 = None

With dict

value = some_dict.get('some_key', undefined)
if value is None:
    log_something("'some_key' was set to None")

if value is undefined:
    # We know that the dict didn't have 'some_key'
    log_something("'some_key' was not set at all")
    value = None

With an object

value = getattr(obj, 'some_attribute', undefined)
if value is None:
    log_something("'obj.some_attribute' was set to None")
if value is undefined:
    # We know that there's no obj.some_attribute
    log_something("no 'some_attribute' set on obj")
    value = None

As I mentioned earlier, custom sentinels come with some caveats. First, they're not keywords like None, so Python doesn't protect them. You can overwrite your undefined above at any time, anywhere in the module it's defined, so be careful how you expose and use them. Next, the instance returned by object() is not a singleton. If you make that call 10 times you get 10 different objects. Finally, usage of a sentinel is highly idiosyncratic. A sentinel is specific to the library it's used in and as such its scope should generally be limited to the library's internals. It shouldn't "leak" out. External code should only become aware of it, if their purpose is to extend or supplement the library's API.

Michael Ekoka
  • 19,050
  • 12
  • 78
  • 79
  • What about: None == thing ? – hkBst Nov 01 '18 at 09:56
  • @hkBst I'm guessing your question is about how python evaluates equality. Have a look at this https://stackoverflow.com/questions/3588776/how-is-eq-handled-in-python-and-in-what-order – Michael Ekoka Nov 01 '18 at 17:02
  • Ah, so IIUC that usually will still end up calling thing.__eq__? In that case I retract my suggestion. – hkBst Nov 02 '18 at 09:56
  • @MichaelEkoka can you share the source for this impressive and useful information. – Anidhya Bhatnagar Dec 25 '18 at 06:46
  • Standard practice. You can find some hints of it from going through the [Python tutorial](https://docs.python.org/3/tutorial/index.html), but reading popular projects' source code is my number one advice to quickly immerse yourself into *[idiomatic Python](https://duckduckgo.com/?q=idiomatic+python)*. – Michael Ekoka Apr 14 '19 at 05:53
  • FWIW, I've taken to setting `undefined = NotImplemented`. Never seen that class *used* anywhere, so it stands out like a sore thumb as a sentinel. You get full singleton `is` behavior from comparing to via `value is undefined`. The only problem is that it's truthy, and yes, it's specific to my code. – JL Peyret Aug 19 '20 at 15:21
  • @JLPeyret There's documentation on the use of `NotImplemented` https://docs.python.org/3/library/constants.html#NotImplemented. I don't think that it would be wise to use it as a sentinel. A good sentinel must be unique and within a well defined scope. The `NotImplemented` class must be used directly as it can't produce an instance. But although the class itself is a singleton, it's a built-in, which makes it available outside any intended scope. It may rear its head in your code from unexpected places and in ways that may even be less predictable than `None`. – Michael Ekoka Nov 20 '20 at 19:05
  • @MichaelEkoka interesting take on the scopes, but I have had exactly the opposite experience. had a different sentinel scheme before ( `undefined = object()`, like everyone else ) but was trying to compare it from 2 scopes - bug fest for hours, precisely the thing a builtin avoids. The only problem I have had is that the class evaluates truthy. `None` however makes a really bad sentinel, IMHO - think for example of `DateofDeath`, that's going to be None in many cases. – JL Peyret Nov 20 '20 at 22:23
72

It's not called null as in other languages, but None. There is always only one instance of this object, so you can check for equivalence with x is None (identity comparison) instead of x == None, if you want.

AndiDog
  • 68,631
  • 21
  • 159
  • 205
  • 29
    I'm going to find a way to break Python by re-instantiating `None`. Then all of those smart people who compared against `NoneType` will triumph! – Zenexer Aug 27 '13 at 03:40
29

In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:

if yourObject is None:  # if yourObject == None:
    ...

if yourString == "":  # if yourString.len() == 0:
    ...

Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.

Anyway, you can have a look at:

Paolo Rovelli
  • 9,396
  • 2
  • 58
  • 37
  • What about `print(0 == False)` returns `True` and `print(0 is False)` returns `False`? – ex3v Dec 13 '13 at 10:24
  • 8
    As far as I know, (0 == false) returns true IN EVERY programming language. That is because false is coded as 0 and "true" as everything that is NOT 0. However, please not that the "is" operator is not the same of the "==" one. This is more or less the same difference between "==" and "equals" in Java. The operator "is", indeed, checks if TWO OBJECTS are the same (the same instance and NOT the same content)! – Paolo Rovelli Dec 13 '13 at 14:43
  • 15
    Paolo, FYI, (0 == false) does not return true in every programming language. A quick counter example would be Scala, where (0 == false) returns false, and I am sure that Scala isn't the only programming language that returns false when comparing a number to a boolean. – Rob Wilton Jul 01 '14 at 14:40
  • 4
    In JavaScript, the reason `0 == false` returns `true` is because the double-equals operator does type coercion. With the triple-equals operator, however, `0 === false` returns `false`, because 'number' and 'boolean' are different types. – jkdev May 18 '16 at 20:41
  • 1
    @PaoloRovelli, in Lua, Ruby, and Clojure, 0 is treated as `true` in conditionals. In Rust and Go, `0` and `false` are different types that can't be compared for equality. – scooter-dangle Aug 15 '17 at 00:23
  • 1
    @jkdev Yes, indeed. That's exactly what I wanted to point out with the Java "==" and "equals" difference. Your example using JavaScript "==" and "===" is actually a better one. :) – Paolo Rovelli May 19 '21 at 13:44
  • 1
    Anyway, my bad. I should have rather written something like "most of the 'classic' programming languages". Indeed, as you well pointed out, this is not always the case. Especially in more recent programming languages (like Rust or Go) which tend to force only "same type" comparisons. – Paolo Rovelli May 19 '21 at 13:52
6

The above answers only will result True for None, but there is such a thing as float('nan'). You could use pandas isnull:

>>> import pandas as pd
>>> pd.isnull(None)
True
>>> pd.isnull(float('nan'))
True
>>> pd.isnull('abc')
False
>>> 

Or without pandas:

>>> a = float('nan')
>>> (a != a) or (a == None)
True
>>> a = None
>>> (a != a) or (a == None)
True
>>> 

The reason this works is because float('nan') != float('nan'):

>>> float('nan') == float('nan')
False
>>> float('nan') != float('nan')
True
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Use f string for getting this solved.

year=None
year_val= 'null' if year is None else  str(year)
print(f'{year_val}')

null
s_mj
  • 530
  • 11
  • 28
1

Simple function to tackle "empty" element in Python:

Code:

def is_empty(element) -> bool:
    """
    Function to check if input `element` is empty.

    Other than some special exclusions and inclusions,
    this function returns boolean result of Falsy check.
    """
    if (isinstance(element, int) or isinstance(element, float)) and element == 0:
        # Exclude 0 and 0.0 from the Falsy set.
        return False
    elif isinstance(element, str) and len(element.strip()) == 0:
        # Include string with one or more empty space(s) into Falsy set.
        return True
    elif isinstance(element, bool):
        # Exclude False from the Falsy set.
        return False
    else:
        # Falsy check.
        return False if element else True

Test:

print("Is empty?\n")
print('"" -> ', is_empty(""))
print('"      " -> ', is_empty("      "))
print('"A" -> ', is_empty("A"))
print('"a" -> ', is_empty("a"))
print('"0" -> ', is_empty("0"))
print("0 -> ", is_empty(0))
print("0.0 -> ", is_empty(0.0))
print("[] -> ", is_empty([]))
print("{} -> ", is_empty({}))
print("() -> ", is_empty(()))
print("[1, 2] -> ", is_empty([1, 2]))
print("(3, 5) -> ", is_empty((3, 5)))
print('{"a": 1} -> ', is_empty({"a": 1}))
print("None -> ", is_empty(None))
print("True -> ", is_empty(True))
print("False -> ", is_empty(False))
print("NaN -> ", is_empty(float("nan")))
print("range(0) -> ", is_empty(range(0)))

Output:

Is empty?

"" ->  True
"      " ->  True
"A" ->  False
"a" ->  False
"0" ->  False
0 ->  False
0.0 ->  False
[] ->  True
{} ->  True
() ->  True
[1, 2] ->  False
(3, 5) ->  False
{"a": 1} ->  False
None ->  True
True ->  False
False ->  False
NaN ->  False
range(0) ->  True
Dheemanth Bhat
  • 4,269
  • 2
  • 21
  • 40
-1

Per Truth value testing, 'None' directly tests as FALSE, so the simplest expression will suffice:

if not foo:
artejera
  • 1,346
  • 1
  • 11
  • 19
  • 5
    No, it won't. That expression will return `True` for _any_ falsy value, not just `None`. – insert_name_here Sep 24 '17 at 23:32
  • True, and the simple "if not foo:" would not answer correctly the original question, as stated. However, python is dynamically typed and invites to reduce syntax protocols, so it seems valid to me, to consider simpler, similar constructs. – artejera Oct 06 '17 at 03:46
-1

Null is a special object type like:

>>>type(None)
<class 'NoneType'>

You can check if an object is in class 'NoneType':

>>>variable = None
>>>variable is None
True

More information is available at Python Docs