Composite Pattern Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Composite Pattern runs in O(n) time and O(n) space, in Python as in every other language.
- ✓No library is required: a node holds a list of children and the branch method recurses. collections.abc supplies the protocols worth conforming to, so implementing __iter__ and __len__ makes a composite work with for, list, sum and unpacking for free.
- ✓Give the node an __iter__ that yields itself and then yields from each child, because yield from makes the recursive generator read as one line and lets every consumer use ordinary iteration.
- ✓The Python trap: CPython has a recursion limit, 1000 by default, and it is not a stack-size guard: it is a counter checked per Python call, so a tree deeper than that raises RecursionError long before the C stack is exhausted.
- ✓Each level of recursion is a Python frame, which is an allocation plus argument binding, so recursive traversal is several times slower than an explicit deque loop over the same nodes.
What Composite Pattern actually is
Composite Pattern in Python: what you actually reach for
Python implementation
import sys
from collections import deque
from dataclasses import dataclass, field
@dataclass
class Node:
name: str
size: int = 0
children: list["Node"] = field(default_factory=list)
def total(self) -> int:
return self.size + sum(c.total() for c in self.children)
def __iter__(self):
yield self
for c in self.children:
yield from c # delegates directly: NOT quadratic
# Deep trees: recursion raises RecursionError at ~1000 frames, and raising
# the limit trades a clean exception for a possible interpreter crash.
def total_iterative(root: Node) -> int:
stack, acc = deque([root]), 0
while stack:
n = stack.pop()
acc += n.size
stack.extend(n.children)
return acc
print(sys.getrecursionlimit()) # 1000Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Composite Pattern?
No library is required: a node holds a list of children and the branch method recurses. collections.abc supplies the protocols worth conforming to, so implementing __iter__ and __len__ makes a composite work with for, list, sum and unpacking for free. For traversal without recursion, collections.deque used as a stack or queue is the idiomatic explicit-frontier structure. os.walk in the standard library is a composite traversal you already use, and it is iterative rather than recursive for exactly the reason below.
What is the most common Python mistake when implementing Composite Pattern?
CPython has a recursion limit, 1000 by default, and it is not a stack-size guard: it is a counter checked per Python call, so a tree deeper than that raises RecursionError long before the C stack is exhausted. Raising it with sys.setrecursionlimit does not make the C stack bigger, so setting it too high converts a clean exception into a hard segmentation fault that kills the interpreter with no traceback. Since 3.12 the limit applies to Python-to-Python calls that no longer consume C stack, which raises the safe ceiling but does not remove the hazard. Deep trees want an explicit stack.
How does Composite Pattern actually perform in Python?
Each level of recursion is a Python frame, which is an allocation plus argument binding, so recursive traversal is several times slower than an explicit deque loop over the same nodes. A generator-based traversal using yield from is noticeably better than nesting plain generators, because yield from delegates directly rather than resuming through every intermediate generator on each item, which is exactly the quadratic behaviour that bites C# below. Memoising an aggregate on the branch turns repeated whole-tree queries from O(n) into O(1) at the cost of invalidation. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.