Flyweight Pattern in Python
Share the common part of thousands of small objects to save memory, keeping only what is unique per object.
- Intrinsic (shared) and extrinsic (unique) state
- A factory that reuses objects
- When the memory saving matters
first callcreates Glyph('A')second callreturns the same object → TrueShare what is the same
The problem
A text editor may show a million characters, a game may draw thousands of trees. Creating a full object for each one wastes memory when most of their data is the same. Flyweight shares the common part.
Think of it like this
Flyweight is like a stamp set for a poster. Instead of carving a new "A" every time it appears, you keep one "A" stamp and press it wherever it is needed. Only the position changes; the stamp is shared.
Glyph(character)🔠 One stamp per letter_cache🗃️ The box of stamps already madesetdefault(character, ...)🔍 Reuse the stamp if it exists, make it if notfirst is second✅ Both A's use the same stamp: TrueThe Flyweight pattern shares one object for all uses of the same intrinsic data and keeps the varying data, such as position, outside the shared object.
Key points
Glyphholds only the shared data: the character._cacheis a class-level dictionary that stores one glyph per character.self._cache.setdefault(character, Glyph(character))returns the stored glyph or stores a new one.- Both calls for
"A"return the same object, sofirst is secondis True.
When should you use it?
- Huge numbers of similar objects: characters in a document, tiles or trees in a game.
- Reducing memory when most object data repeats.
- Caching immutable values that many parts of a program use.
When not to use it
- Few objects: the cache adds complexity for no real saving.
- Shared objects that callers modify: one change would affect every use.
Example code
class Glyph:
# Flyweight: share repeated intrinsic state between many uses.
def __init__(self, character): self.character = character
class GlyphFactory:
_cache = {}
def get(self, character):
# Reuse immutable intrinsic state.
return self._cache.setdefault(character, Glyph(character))
factory = GlyphFactory()
first = factory.get("A")
second = factory.get("A")
print(first is second)
print(first.character)
Result of running the code
True
A
Code explanation
GlyphFactory keeps a dictionary that maps each character to one Glyph object. setdefault returns the existing glyph for a character if there is one and stores a new glyph otherwise, so asking for "A" twice returns the same object. Data that differs per use, such as a position, would be passed in when drawing instead of being stored in the glyph.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Storing unique data in the shared object
If each glyph stored its own position, sharing would mix positions up.
glyph = factory.get("A")
glyph.x = 10 # changes every A
glyph = factory.get("A")
draw(glyph, x=10, y=20)
Finished this lesson?
Mark it as learned to track your progress.