The Flyweight Pattern in Python: Sharing State Across Thousands of Objects

This article explains how the Flyweight pattern separates shared from per-object state, measures the memory it saves, and builds a weak-valued cache of immutable flyweights in Python.

A bright green snake with white flecks wrapped around a dark branch, its head lowered beside green leaves
Photo by Vlada on Unsplash

A program that creates many objects with largely identical data stores the same values over and over, and its memory grows with the number of objects rather than with the amount of distinct information. The present article examines the Flyweight pattern, which separates the state that many objects share from the state that belongs to each one, keeps a single copy of the former and lets every object refer to it. It measures the saving with tracemalloc, builds a cache of shared objects that releases them when no one uses them, shows where CPython itself applies the pattern, and describes the conditions, above all immutability, without which sharing becomes a source of errors. Storing each distinct piece of data once, however many objects use it, is the secret weapon of the Flyweight pattern.

Same Model, Different Position: Intrinsic and Extrinsic State

The pattern divides the data of an object into two parts. The intrinsic state is identical among many objects and does not depend on the context, such as the name, colour and texture of a kind of tree; the extrinsic state varies from object to object, such as the position of each tree in a forest. The flyweight holds only the intrinsic state and is shared, while each light object holds the extrinsic state and a reference to its flyweight.

import tracemalloc
from dataclasses import dataclass

@dataclass(frozen=True, slots=True, weakref_slot=True)
class TreeType:
    name: str
    colour: str
    texture: bytes

class Tree:
    __slots__ = ("x", "y", "kind")

    def __init__(self, x, y, kind):
        self.x, self.y, self.kind = x, y, kind

def plant(count, kinds):
    return [Tree(i, i, kinds(i)) for i in range(count)]

NAMES = ("Oak", "Pine", "Birch")
SHARED = {name: TreeType(name, "green", bytes(4096)) for name in NAMES}

def own_copy(i):
    name = NAMES[i % 3]
    return TreeType(name, "green", bytes(4096))

def shared(i):
    return SHARED[NAMES[i % 3]]

def measure(kinds):
    tracemalloc.start()
    forest = plant(10_000, kinds)
    size, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return size, len({id(tree.kind) for tree in forest})

copied_size, copied_kinds = measure(own_copy)
shared_size, shared_kinds = measure(shared)
print(copied_kinds, shared_kinds)          # Output: 10000 3
print(shared_size * 20 < copied_size)      # Output: True

Ten thousand trees that each own a copy of a 4 096-byte texture occupied about 43 megabytes in the measurement of this article, whereas the same trees sharing three TreeType objects occupied less than one megabyte, about forty-five times less. The light object Tree declares __slots__, so that its own cost is three references and no dictionary, a technique examined in the article devoted to __slots__. The flyweight TreeType is a frozen data class, which matters as much as the saving itself, for reasons explained in the pitfalls.

A Cache of Flyweights That Releases Them

The objects must be shared through a single point of creation, which returns an existing flyweight when one with the same intrinsic state exists and creates it otherwise. A plain dictionary would keep every flyweight alive for the whole life of the program, even when no object refers to it any longer; a WeakValueDictionary holds its values through weak references, so that an entry disappears when its flyweight is no longer used, the behaviour described in the article devoted to weak references.

import gc
import weakref
from dataclasses import dataclass

@dataclass(frozen=True, slots=True, weakref_slot=True)
class TreeType:
    name: str
    colour: str
    texture: bytes

_types = weakref.WeakValueDictionary()

def tree_type(name, colour):
    key = (name, colour)
    kind = _types.get(key)
    if kind is None:
        kind = TreeType(name, colour, bytes(4096))
        _types[key] = kind
    return kind

forest = [tree_type(("Oak", "Pine")[i % 2], "green") for i in range(1_000)]
print(len(_types))                                   # Output: 2
print(tree_type("Oak", "green") is forest[0])        # Output: True

del forest
gc.collect()
print(len(_types))                                   # Output: 0

A thousand requests produce two flyweights, and a later request for the same key returns the existing object, as the identity check shows. Once the forest is deleted, no strong reference to the flyweights remains and the cache empties itself. The method get followed by an explicit assignment is deliberate: it keeps a strong reference in the local variable kind while the new object is stored, so that the entry cannot vanish between its creation and its return.

Flyweights Inside CPython

The interpreter applies the same idea to some of its most frequent objects. CPython creates the integers from -5 to 256 once and reuses them, keeps a single None, True and False, and interns many strings, a mechanism analysed in the article devoted to string interning.

a, b = int("256"), int("256")
c, d = int("257"), int("257")
print(a is b)   # Output: True
print(c is d)   # Output: False
print(a == b and c == d)  # Output: True

Both conversions of "256" return the same cached object, whereas each conversion of "257" creates a new one, although all four values compare as equal. The range of cached integers is an implementation detail of CPython, not a guarantee of the language, which is why code must compare values with == and reserve is for identity, as with None.

Pitfalls of the Flyweight Pattern

Sharing introduces dependencies between objects that would otherwise be independent, and each of them becomes a possible error. Six pitfalls are distinguished, which are the following:

  1. Mutable flyweights. A change to a shared object affects every object that refers to it; the intrinsic state must be immutable, for example with frozen=True.
  2. Extrinsic state inside the flyweight. A value that differs from object to object, stored in the flyweight, is silently overwritten by the next user.
  3. Caches that never shrink. A dictionary of flyweights keeps every one of them alive; weak values let unused flyweights be collected.
  4. Slotted classes without weak references. A class with __slots__, or a data class with slots=True, cannot be the target of a weak reference unless it reserves a slot for it, with weakref_slot=True or __weakref__ in __slots__.
  5. Identity tests on values. Code that compares numbers or strings with is works by accident for cached values and fails for others.
  6. Sharing without need. When objects have little repeated data, the factory and the split between states add complexity without a measurable saving.

The fourth pitfall is reproduced in the following example.

import weakref
from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Compact:
    name: str

try:
    weakref.ref(Compact("Oak"))
except TypeError as error:
    print(error)  # Output: cannot create weak reference to 'Compact' object

@dataclass(frozen=True, slots=True, weakref_slot=True)
class CompactWithRef:
    name: str

print(weakref.ref(CompactWithRef("Oak")) is not None)  # Output: True

The first class has no space for weak references, so the cache of the previous section would reject its instances with TypeError. The parameter weakref_slot, available since Python 3.11, adds that space while keeping the memory advantages of slots.

Choosing Whether to Share

Consequently, the pattern pays off only when many objects repeat the same data, and the standard library already covers several of its cases, as the following table summarizes.

Situation Recommended approach
Many objects repeat large, immutable data Flyweight with a factory and frozen intrinsic state
Shared objects may stop being used weakref.WeakValueDictionary as the cache
Shared objects live for the whole program functools.cache on the factory function
Many repeated strings built at run time sys.intern
Many small objects without repeated data __slots__, not Flyweight
Numerical data in bulk array or a structure of columns instead of one object per item

Conclusion

It is concluded that the Flyweight pattern reduces memory by storing intrinsic state once and leaving only extrinsic state in each object, and that in Python its correct form combines frozen data classes for the shared part, slotted classes for the light part and a weak-valued cache that releases flyweights when nobody uses them. This magic rests on immutability, since a single change to a shared object would reach every object that refers to it. The question of which part of a program creates such shared objects and how they reach the code that uses them, instead of each module creating its own, belongs to dependency injection, which is developed in a future article of this series.