Fewer None Checks? The Null Object Pattern in Python

This article explains how the Null Object pattern replaces None with a do-nothing collaborator in Python, how it differs from Special Case objects and sentinels, and when it hides errors instead of removing checks.

A green tree python with white flecks rests coiled around a branch, its head laid on its own coils against a dark background.
Photo by Tirza van Dijk on Unsplash

A function that may lack a collaborator usually returns or stores None, and every caller must then remember to check it before calling a method, or receive AttributeError: 'NoneType' object has no attribute .... The present article addresses the Null Object pattern, described by Bobby Woolf in the second half of the 1990s, which replaces that None with an object that offers the same interface and does nothing. It distinguishes the pattern from the closely related Special Case, shows the null objects that the standard library already provides, and analyses the conditions under which the pattern hides errors instead of removing checks. Turning the absence of a collaborator into an ordinary object, so that the code which uses it needs no special case at all, is the secret weapon of the Null Object pattern.

Empty Equipment Slot: An Object That Stands for Nothing

The checks appear because None has no methods: a class that accepts an optional notifier must test it before every use, and each forgotten test becomes an AttributeError at run time. A null object moves that decision to a single place, the moment in which the collaborator is chosen, by supplying a class with the same methods whose bodies do nothing. The following example gives an order an optional notifier and uses one shared null instance as the default.

class EmailNotifier:
    def __init__(self):
        self.sent = []

    def notify(self, message):
        self.sent.append(message)


class NullNotifier:
    def notify(self, message):
        pass


NULL_NOTIFIER = NullNotifier()


class Order:
    def __init__(self, total, notifier=NULL_NOTIFIER):
        self.total = total
        self.notifier = notifier

    def pay(self):
        self.notifier.notify(f"paid {self.total}")
        return "paid"


email = EmailNotifier()
print(Order(30, email).pay(), email.sent)  # Output: paid ['paid 30']
print(Order(10).pay())                     # Output: paid

The method pay contains no condition: it calls notify on whatever it received, and the null notifier accepts the call and discards it. Sharing one instance is safe here because NullNotifier holds no state, which is the only condition under which a null object may be reused as a module-level constant.

Null Objects That Return Values

A method that only acts can do nothing, but a method that returns something must return a neutral value, such as an empty collection, zero or False; returning None would merely move the original check to the caller. When the substitute carries meaningful behaviour of its own, such as a guest who has a name but no permissions, the design is what Martin Fowler calls the Special Case pattern, of which the null object is the simplest form. The following example declares the expected interface as a protocol, the mechanism examined in the article devoted to typing.Protocol, so that a type checker verifies that the substitute keeps up with the real class.

from typing import Protocol


class User(Protocol):
    name: str

    def can(self, action: str) -> bool: ...


class Member:
    def __init__(self, name, permissions):
        self.name = name
        self.permissions = frozenset(permissions)

    def can(self, action):
        return action in self.permissions


class Guest:
    name = "guest"

    def can(self, action):
        return False


GUEST = Guest()
USERS = {123: Member("alice", {"read", "write"})}


def find_user(user_id) -> User:
    return USERS.get(user_id, GUEST)


for user_id in (123, 999):
    user = find_user(user_id)
    print(user.name, user.can("write"))
# Output: alice True
# Output: guest False

The function find_user always returns an object of the declared interface, so the loop prints and checks permissions without asking whether a user was found. The difference from a sentinel, as described in the article devoted to the sentinel pattern, is essential: a sentinel exists only to be compared with is, whereas a null object exists precisely so that nobody needs to compare it.

Null Objects in the Standard Library

Python already ships two widely used null objects. logging.NullHandler, available since Python 3.1, is the handler that libraries attach to their loggers so that, when the application configures no logging, their messages are discarded instead of reaching the fallback handler that writes to standard error. contextlib.nullcontext, added in Python 3.7 and usable with async with since Python 3.10, replaces an optional context manager, a protocol described in the article devoted to context managers. The following example shows both.

import contextlib
import io
import logging
import threading


def append_all(target, items, lock=None):
    with lock if lock is not None else contextlib.nullcontext():
        target.extend(items)


shared = []
append_all(shared, [1, 2], threading.Lock())
append_all(shared, [3])
print(shared)  # Output: [1, 2, 3]

buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
    logging.getLogger("loud").warning("disk almost full")
    quiet = logging.getLogger("quiet")
    quiet.addHandler(logging.NullHandler())
    quiet.warning("disk almost full")
print(repr(buffer.getvalue()))  # Output: 'disk almost full\n'

The function append_all uses a single with statement whether or not a lock was supplied, and only the logger without handlers reaches standard error, so the captured text contains one message instead of two.

Pitfalls of the Null Object Pattern

A null object removes checks by making absence indistinguishable from presence, so every error of the pattern comes from situations in which that distinction still matters. Six pitfalls are distinguished, which are the following:

  1. Hiding real errors. When absence is a bug, such as a missing configuration that must exist, a silent substitute postpones the failure; raising an exception is the correct response.
  2. Black-hole objects. A generic class whose __getattr__ returns itself accepts any attribute, so a misspelt method name produces no error at all.
  3. Interface drift. When the real class gains a method and the null class does not, the AttributeError reappears; a protocol or an abstract base class with a type checker prevents it.
  4. Unsafe return values. A null method that returns None instead of an empty or neutral value simply moves the check to the caller.
  5. Shared mutable state. A null object reused as a single instance must hold no state, or every user of the default shares it.
  6. Residual checks. The null object is truthy and is not None, so callers that still test is None or truthiness treat it as a real collaborator, and defining __bool__ to return False reintroduces the checks that the pattern was meant to remove.

The second pitfall and the cost of the pattern are reproduced in the following example.

import timeit


class BlackHole:
    def __getattr__(self, name):
        return self

    def __call__(self, *args, **kwargs):
        return self


class NullNotifier:
    def notify(self, message):
        pass


hole = BlackHole()
print(type(hole.notfy("paid").total).__name__)  # Output: BlackHole
try:
    NullNotifier().notfy("paid")
except AttributeError as error:
    print(error)  # Output: 'NullNotifier' object has no attribute 'notfy'

null = NullNotifier()
missing = None


def check_none():
    if missing is not None:
        missing.notify("x")


def call_null():
    null.notify("x")


t_none = min(timeit.repeat(check_none, number=1_000_000, repeat=5))
t_null = min(timeit.repeat(call_null, number=1_000_000, repeat=5))
print(t_null > t_none)  # Output: True

The black hole swallows the misspelt notfy and even the attribute read after it, whereas the explicit null class reports the mistake at once. On CPython 3.12, an is not None test took about 18 nanoseconds and a call to an empty method about 29, so the pattern costs one method call per use, a difference that matters only in the tightest loops.

Choosing How to Represent Absence

Consequently, a null object is appropriate when absence is a normal situation and doing nothing is the correct behaviour, as the following table summarizes.

Situation Recommended approach
An optional collaborator whose absence means doing nothing A null object with the same methods
A substitute with meaningful default behaviour A Special Case object, such as a guest user
An optional lock or context manager contextlib.nullcontext
A library logger without configured output logging.NullHandler
Absence that indicates a bug An exception
Telling an omitted argument from None A sentinel compared with is
A value that callers must handle explicitly None with an optional type annotation

Conclusion

It is concluded that a null object replaces None with a collaborator that offers the same interface and does nothing, that methods which return must return neutral values, and that the standard library applies the idea in logging.NullHandler and contextlib.nullcontext. This magic is appropriate only when absence is legitimate: black-hole implementations swallow typos, unsynchronised interfaces bring the errors back, and absence that signals a bug must still raise. Storing large sequences of numbers in a compact typed buffer, instead of a list of separate objects, is the purpose of the array module, which is developed in a future article of this series.