Python Design Patterns

Flyweight Pattern in Python

Share the common part of thousands of small objects to save memory, keeping only what is unique per object.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • Intrinsic (shared) and extrinsic (unique) state
  • A factory that reuses objects
  • When the memory saving matters
factory.get("A") twice
first callcreates Glyph('A')
second callreturns the same object → True
1,000 letter A's on a page share one Glyph object.

Share 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.

From a stamp set to code
Glyph(character)🔠 One stamp per letter
_cache🗃️ The box of stamps already made
setdefault(character, ...)🔍 Reuse the stamp if it exists, make it if not
first is second✅ Both A's use the same stamp: True
Share the repeated part; supply the unique part when using it.
In one sentence

The 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

  1. Glyph holds only the shared data: the character.
  2. _cache is a class-level dictionary that stores one glyph per character.
  3. self._cache.setdefault(character, Glyph(character)) returns the stored glyph or stores a new one.
  4. Both calls for "A" return the same object, so first is second is 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

Run code →
main.py
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)
Get a Run button for this example

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.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Storing unique data in the shared object

If each glyph stored its own position, sharing would mix positions up.

Problem
glyph = factory.get("A")
glyph.x = 10  # changes every A
Fix
glyph = factory.get("A")
draw(glyph, x=10, y=20)

Finished this lesson?

Mark it as learned to track your progress.