Keep a collection from leaking

Lesson 9 of 19 · Python Object Design

A method can validate changes and still expose a route around those checks if it returns its actual mutable list. Instead, an object can copy the outer list on both entry and exit:

class DisplayLabels:
    def __init__(self, labels):
        self._labels = list(labels)

    def add(self, label):
        if not label.strip():
            raise ValueError("label must not be blank")
        self._labels.append(label)

    def labels(self):
        return self._labels.copy()

original = ["North"]
display = DisplayLabels(original)
original.append("Outside")
view = display.labels()
view.append("Also outside")
display.add("South")
print(display.labels())
print(original)
print(view)

Output:

['North', 'South']
['North', 'Outside']
['North', 'Also outside']

list(labels) creates a new outer list when the object is initialized. .copy() creates another outer list for the caller. Appending to either outside list therefore does not append to _labels. The method add is the supported path for later additions. This example assumes strings and does not validate the initial labels; a stronger invariant that all labels are nonblank would also require validation during initialization.

These are shallow copies: they copy references to elements, not the elements themselves. Strings are immutable, so that is sufficient for this example. If elements were mutable lists or objects, changing one through a copied list could still be visible through the other. Deep copying may help in some designs, but is not automatically appropriate for every object or relationship.

original -> list A -> "North"
internal -> list B -> "North"     (separate outer lists)
view     -> list C -> "North"

The underscore is still a convention: a caller can deliberately reach _labels. Copying protects the normal interface against accidental aliasing, not hostile code.

Chapter contents