Python Null: Use None Correctly

Python does not have a null keyword. The Python name for the absence of a value is None. If you come from JavaScript, Java, SQL, or JSON, this is the main translation to remember: Python code writes None, while JSON text writes null.

The official Python documentation defines None as a built-in constant. The language reference explains identity comparisons, and the json module documentation shows how JSON null maps to Python None.

Use None when a result is intentionally absent, not yet known, or not supplied by the caller. It is common for missing dictionary lookups, optional function arguments, parser results, search results, and placeholder return values.

Do not use None as a replacement for every empty value. An empty string, an empty list, zero, and False all carry different meaning. Mixing them with None can make later checks confusing, especially when a real value is allowed to be empty.

The safest habit is to choose one meaning for None in each API. If it means “not found”, keep that meaning clear. If an empty result is valid, return the empty result instead of None. That makes calling code easier to test.

Create And Check None

None is a singleton object. There is only one None object in a Python process, so identity checks are the standard way to test for it.

missing = None

print(missing is None)
print(missing is not None)
print(bool(missing))

The first line prints True because missing refers to None. The final line prints False because None is falsy in truth-value testing.

That falsy behavior is useful, but it can also hide important distinctions. If an empty string or zero is valid in your program, do not use a broad truth check to detect missing data.

Use is None Instead Of Equality

For None, prefer is None and is not None. Equality can be customized by objects, while identity asks whether the object really is None.

class LooksEqual:
    def __eq__(self, other):
        return other is None

item = LooksEqual()

print(item == None)
print(item is None)

The first check can be influenced by __eq__(). The identity check cannot be fooled by custom equality behavior.

This is why style guides and experienced Python programmers write if value is None: instead of if value == None:. It is clearer and more exact.

Notice Implicit None Returns

A function returns None when it reaches the end without a return statement. Many functions that mutate an object in place follow this style.

def add_tag(tags, tag):
    tags.append(tag)

tags = []
result = add_tag(tags, "python")

print(tags)
print(result is None)

The list changed, but the function result is None. This pattern is common with mutating methods such as list.append() and dict.update().

If a helper changes an object in place, returning None can signal that callers should inspect the object, not the result. If the helper creates a new object, returning the new object is usually more convenient.

Use None For Optional Arguments

None is a good default when a function needs to create a fresh list, dictionary, or set for each call. The function can detect the missing argument and allocate inside the body.

def collect(value, items=None):
    if items is None:
        items = []
    items.append(value)
    return items

print(collect("alpha"))
print(collect("beta"))

Each call receives a fresh list when the caller does not provide one. This avoids shared state between calls.

Use this pattern for optional containers. It keeps the public function easy to call while avoiding accidental reuse of the same object across separate calls.

Convert JSON null To None

JSON uses null, but Python code uses None. The standard json module handles the conversion in both directions.

import json

payload = json.loads('{"name": "Ada", "nickname": null}')

print(payload["nickname"] is None)
print(json.dumps({"nickname": None}, sort_keys=True))

After loading JSON, test the parsed value with is None. When dumping Python data back to JSON, None becomes null in the output text.

This conversion is one reason the words are often confused. Keep the spelling tied to the format you are writing: None in Python source, null in JSON text.

Separate Missing From Falsy

Sometimes a real value can be falsy. A timeout of 0, an empty label, or False can all be valid. In those cases, use a unique sentinel object so missing data is not confused with present data.

not_found = object()
settings = {"timeout": 0, "label": ""}

for key in ["timeout", "label", "retries"]:
    value = settings.get(key, not_found)
    if value is not_found:
        print(key, "missing")
    else:
        print(key, repr(value))

The sentinel is different from every real setting, including falsy settings. That lets the code keep zero and empty text while still detecting the absent key.

Reach for this pattern when None itself can be a valid stored value, or when several falsy values need to stay distinct. It is more explicit than if not value, and it gives future readers a clear missing-data branch.

The practical rule is short: write None in Python, use is None for checks, let json translate null, and decide whether missing, empty, zero, and false each need separate handling.

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
elijah.ho
elijah.ho
4 years ago

It’s useful to me

Pratik Kinage
Admin
4 years ago
Reply to  elijah.ho

I’m glad it helped you 🙂

Regards,
Pratik