Ch 9 — Builtins & Patterns
Ch 9 — Builtins & Patterns
Python ships with a powerful set of built-in functions and language patterns that Aryan has been reaching for without fully naming. This chapter names them, explains their mechanics, and shows how they combine into the polished internal logic of the RAM manager — from validating a list of thresholds with all() to scoping helper functions safely inside other functions.
any and all
any(iterable) returns True if at least one element is truthy. all(iterable) returns True if every element is truthy.
thresholds_valid = [80, 90, 95]
all(0 < t <= 100 for t in thresholds_valid) # True — all in range
processes = ["chrome", "", "electron"]
any(p for p in processes) # True — at least one non-empty string
alerts = [False, False, True, False]
any(alerts) # True — at least one critical event
all(alerts) # False — not all are criticalisinstance
Check type without using type() ==. Works with inheritance.
def display(value):
if isinstance(value, (int, float)):
print(f"{value:.2f}")
elif isinstance(value, str):
print(value)
else:
raise TypeError(f"Cannot display type {type(value)}")
isinstance(42, int) # True
isinstance(42, (int, float)) # True — tuple of typesString Method Power Moves
name = " com.apple.WebKit.Networking "
name.strip() # 'com.apple.WebKit.Networking'
name.strip().split(".") # ['com', 'apple', 'WebKit', 'Networking']
name.strip().lower() # 'com.apple.webkit.networking'
# Check conditions
"chrome".startswith("ch") # True
"kernel_task".endswith("task") # True
"4821".isdigit() # True
"4821".isnumeric() # True
" ".isspace() # TrueUnpacking
Assign multiple variables from a sequence in one line.
snapshot = ("chrome", 4821, 1024.5, 73.5)
name, pid, rss_mb, pct = snapshot # exact match
# Star unpacking — absorb the middle
first, *middle, last = [10, 20, 30, 40, 50]
# first=10, middle=[20,30,40], last=50
# Swap without a temp variable
a, b = b, a
# Ignore values with _
_, pid, rss_mb, _ = snapshot # only want pid and rss_mbScope
Python resolves names in the LEGB order: Local → Enclosing → Global → Built-in.
THRESHOLD = 80 # Global
def check_ram(used_pct):
label = "WARN" if used_pct > THRESHOLD else "OK" # reads Global
return label
def update_threshold(new_val):
global THRESHOLD # explicitly modify the global
THRESHOLD = new_valAvoid overusing global — pass values as arguments instead.
Nested Functions
A function defined inside another function. Useful for encapsulating helpers that are only meaningful in context.
def build_report(snapshots):
def format_row(snap):
return f"{snap.name:<20} {snap.rss_mb:>8.1f} MB"
rows = [format_row(s) for s in snapshots]
return "\n".join(rows)format_row is invisible outside build_report — clean encapsulation.
Closures
A nested function that captures variables from its enclosing scope.
def make_threshold_checker(limit):
def check(value):
return value > limit # 'limit' captured from outer scope
return check
warn_check = make_threshold_checker(80)
crit_check = make_threshold_checker(95)
warn_check(87) # True
crit_check(87) # FalseSet Comprehensions
# Unique process names from snapshots
unique_names = {snap.name for snap in snapshots}
# Unique names of heavy processes
heavy_names = {snap.name for snap in snapshots if snap.rss_mb > 512}Generator Expressions
Like list comprehensions but lazy — they yield one item at a time without building the full list. Memory-efficient for large datasets.
# Sum RSS without building an intermediate list
total_rss = sum(snap.rss_mb for snap in snapshots)
# Find the first heavy process
first_heavy = next(
(s for s in snapshots if s.rss_mb > 1024),
None # default if nothing found
)collections Module
from collections import defaultdict, Counter, deque
# defaultdict — no KeyError on missing keys
history = defaultdict(list)
for snap in snapshots:
history[snap.name].append(snap.rss_mb)
# Counter — count occurrences
proc_counts = Counter(snap.name for snap in all_snapshots)
top3 = proc_counts.most_common(3)
# deque — efficient fixed-size sliding window
recent = deque(maxlen=60) # last 60 seconds of RAM %
recent.append(get_ram_pct())LEGB Scope Model
flowchart TD
A[Name lookup] --> B{In Local scope?}
B -->|Yes| C[Use local variable]
B -->|No| D{In Enclosing scope?}
D -->|Yes| E[Use enclosing variable — closure]
D -->|No| F{In Global scope?}
F -->|Yes| G[Use module-level variable]
F -->|No| H{In Built-in scope?}
H -->|Yes| I["Use builtin: len, print, sum …"]
H -->|No| J[NameError]Builtin & Pattern Toolkit
mindmap
root((Builtins & Patterns))
Predicates
any
all
isinstance
Unpacking
tuple unpacking
star unpacking
swap idiom
Scope
LEGB rule
global keyword
closures
Comprehensions
list
dict
set
generator
collections
defaultdict
Counter
dequeKey Takeaways
any()/all()cleanly validate collections of conditions without explicit loops.isinstance()is the right way to check types — it respects inheritance.- Unpacking (including star
*) assigns multiple variables from sequences in one readable line. - Python resolves names via LEGB (Local → Enclosing → Global → Built-in); prefer passing values over
global. - Nested functions encapsulate helper logic; closures capture outer variables for reuse.
- Generator expressions are memory-efficient — prefer them over list comprehensions when you only need to iterate once.
collections.defaultdict,Counter, anddequesolve common patterns (grouping, counting, sliding windows) without boilerplate.