itertools and functools in practical pipelines
Compose iterators while keeping consumption and caching visible.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain use small transformations
- Apply grouping has an ordering assumption
- Reason about clarity before cleverness
Use small transformations
An iterator yields values in sequence and remembers how far it has been consumed. Combining iterables lazily avoids building a second combined list, but it does not make consumed values repeatable.
Understand first
A report may read one source and then another while taking only a small preview. chain and islice express that flow without first concatenating all values. Start with list iteration and function calls; distinguish the source collection from its iterator.
Words you will see
- Iterable
- An object from which an iterator can be requested.
- Iterator
- An object that supplies the next value and advances its state.
- Lazy
- Producing a value when requested instead of preparing all results in advance.
Follow the consumer, not just the producer
chain first visits left and then right. islice(stream, 2) requests two values, so converting that slice to a list consumes 2 and 4. Converting the remaining stream to a list continues with 6 and 8; it does not restart.
left and right still contain their original entries. The iterator's progress is separate from list ownership. An empty source contributes nothing. Calling list(stream) twice would make the second call empty after the first has exhausted it.
Choose when materialisation is worthwhile
A list is appropriate when you need indexing or several passes over a bounded result. An iterator is useful for one-pass processing and large sources. list at the end is an explicit choice to retain the selected values; laziness upstream does not remove that allocation.
islice accepts nonnegative positions and consumes skipped positions as it advances. It cannot rewind or provide negative slicing like a list. A pipeline also retains its source objects; because these fixtures are already lists, this example does not claim constant total application memory.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
stream = chain(left, right)Prepare a lazy left-then-right traversal.
print(list(islice(stream, 2)))Request and retain two values for the preview.
print(list(stream))Continue rather than restart the chain.
print(left, right)Show that advancing an iterator did not pop either source list.
itertools.chain streams multiple iterables; islice takes a bounded window without requiring a list. A pipeline stays understandable when each step has one responsibility and its consumption behaviour is explicit.
Conceptual consumption of a combined stream
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Sources[1, 2] then [3, 4] supply values.
- Windowislice consumes 1, 2 and 3.
- RemainderOnly 4 remains in that iterator.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Take across the source boundary.
Try: Change islice(stream, 2) to islice(stream, 3).
The preview is [2, 4, 6] and the remainder is [8].
Try an empty source.
Try: Set left = [].
The preview consumes [6, 8] and the remainder is empty; right stays unchanged.
Before you move on
For chain([], [9, 9]), what remains after taking one value with islice?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
One 9 remains. The empty first source adds nothing, and repeated values remain separate observations.
Grouping has an ordering assumption
groupby groups adjacent runs of equal keys. It does not collect every equal key from the whole input unless that input has already been arranged that way.
Understand first
A log may need lengths of consecutive service runs, while a summary needs totals per service. Those are different contracts. groupby is a run tool; a dictionary or Counter is usually clearer for global totals.
Words you will see
- Run
- A consecutive stretch of equal keys.
- Group iterator
- A one-pass view over the current run.
- Aggregation
- Combining observations into a summary such as a count.
Keep adjacency visible
The first two a values form one run, followed by a b run and another a run. Consuming each group immediately with list lets len measure its run length. Three runs therefore appear, even though only two distinct labels exist.
sorted(values) creates a separate list where all a values are adjacent. groupby on that list yields total a count three and b count one, but loses the original run sequence. sorted does not mutate values; values.sort() would.
Consume a group before advancing
The group iterators share the underlying input with groupby. Advancing the outer iterator invalidates access to earlier unconsumed values. Store each group's materialised contents if you need to retain it, or compute its small summary immediately as this program does.
Sorting n items generally adds O(n log n) comparison work and O(n) retained result space. For global counts without sorted-key output, a mapping can aggregate in one pass on ordinary hash-table assumptions. Choose based on whether order or global identity defines a group.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
values = ['a', 'a', 'b', 'a']Include a repeated key separated by b.
runs = [(key, len(list(group))) for key, group in groupby(values)]Fully consume each consecutive group before moving on.
print([(key, len(list(group))) for key, group in groupby(sorted(values))])Show how sorting changes the grouping question.
print(values)Verify that sorted left source order alone.
itertools.groupby groups consecutive equal keys, not every equal key across the complete input. Sort first when that is the intended contract, or aggregate with a dict. Sorting may materialise the input and changes the memory profile.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Merge adjacent runs.
Try: Set values = ['a', 'a', 'a', 'b'].
Both calculations now show [('a', 3), ('b', 1)].
Use an empty input.
Try: Set values = [].
Both group summaries and the unchanged source print as empty lists.
Before you move on
How many runs are in the fresh sequence ['x', 'y', 'x', 'x', 'y']?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Four: x of length 1, y of length 1, x of length 2 and y of length 1. There are only two distinct keys, but four consecutive runs.
Take a bounded combined stream
A pipeline can consume a bounded preview and then continue, while a reduction combines values into one result. Choose a built-in operation when it states the intent more directly.
Understand first
The original program joins two sources, previews three values, then calculates an unrelated sum. It lets you distinguish iterator state from an accumulator's state. Learn ordinary addition and lambdas before choosing reduce for a general combination.
Words you will see
- Reduction
- Combining successive inputs into one accumulated result.
- Accumulator
- The running result passed into the next reduction step.
- Initial value
- The accumulator used before any input has been consumed.
Trace the two independent calculations
chain supplies 1, 2, 3 and 4 in that order. The first list conversion asks islice for three values, so it prints [1, 2, 3]. The remaining chain supplies only 4. No relation exists between this exhausted stream and the separate list passed to reduce.
reduce starts with 0. The lambda adds 1 to make 1, then 2 to make 3, then 3 to make 6. The initial value also defines the empty-input result: the same reduction over [] returns 0. Without an initial value, an empty reduction raises TypeError.
Prefer the intent-revealing operation
sum([1, 2, 3]) expresses this arithmetic more plainly. reduce earns its complexity when a clear binary operation lacks a better built-in. A short loop may be easier when each step needs validation or useful error context.
A reduction retains an accumulator, not necessarily constant memory: an accumulator that grows a list still grows with input. Here it is a small integer and the source is a literal list. All examples are deterministic and local; no claim about parallelism or processing speed is made.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
stream = chain([1, 2], [3, 4])Combine two iterable sources in order.
print(list(islice(stream, 3)))Consume three entries for a bounded preview.
print(list(stream))Print the one unconsumed entry.
print(reduce(lambda a, b: a + b, [1, 2, 3], 0))Add three values from an independent list, starting with zero.
islice consumes three values; only the fourth remains. For this sum, the built-in sum would be clearer than reduce.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Use the clearer sum.
Try: Replace reduce(lambda a, b: a + b, [1, 2, 3], 0) with sum([1, 2, 3]).
The final output stays 6 with simpler intent.
Take nothing.
Try: Change islice(stream, 3) to islice(stream, 0).
The preview is empty and all four values remain in stream.
Before you move on
What does this addition reduction return for [5, 5] with initial value 10?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
20: the initial accumulator participates, then each 5 is added once. It is not a fallback used only for empty input.
Where this idea earns its place
Iterator tools make pipelines compact when each stage has an explicit consumption contract. They are valuable for streaming logs or combining record sources, but the apparent simplicity can conceal a one-time cursor, delayed exceptions or retained buffers. Name intermediate stages while learning so each transformation remains inspectable.
Follow the mechanism step by step
chain requests values from each input in turn; islice consumes the values it passes or skips rather than indexing a reusable list. groupby creates groups of consecutive equal keys, not a global index. functools helpers can configure or cache a function, but they do not change whether its inputs or results are safe to reuse.
Work through a concrete application
Combine two small streams, consume only the first three values, then inspect what remains. This demonstrates that a downstream consumer advances the same iterator. For global grouping, either sort deliberately before groupby or aggregate with a mapping. State whether input order must be preserved and whether materialisation is permitted.
Failure cases and misleading shortcuts
Calling list or sum while debugging can exhaust a stream before the actual consumer sees it. A cache can return stale mutable results or retain unbounded keys. reduce can obscure a transformation for which sum, any or a clear loop already communicates intent. Laziness changes when errors are raised, which affects transaction and resource boundaries.
Cost, ownership and alternatives
A generator avoids storing all output only if downstream work also streams. tee buffers when consumers diverge, and sorting requires retained data. Cached calls trade recomputation for memory and invalidation complexity. Include these retained structures when claiming a pipeline is bounded rather than counting only its visible source iterator.
Verify the contract
Test two traversals, partial consumption, an empty source and a failure after several yielded values. Compare consecutive grouping with global grouping on an input whose keys recur later. For cached functions, test freshness, eviction and whether callers can mutate a cached result seen by another caller.
Transfer question: Why can tee use substantial memory even though both outputs are iterators?
When one consumer runs far ahead, tee must retain values until the slower consumer reaches them. The gap, not merely the number of consumers, determines buffering. A one-pass combined report or explicit bounded materialisation can be more predictable.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Take a bounded combined stream
Without copying the worked code, reproduce its observable contract: islice consumes three values; only the fourth remains. For this sum, the built-in sum would be clearer than reduce. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guide: consume a bounded preview
Combine two iterables and take no more than a requested number of values.
The contract
- Inputs left and right are finite iterables, and limit is a nonnegative integer.
- Return a fresh list of the first limit values from left then right, preserving duplicates. Zero returns []; a large limit returns everything.
- Consume only requested values from one-shot sources. Source lists are not mutated. Never materialise the entire combined stream before slicing.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- cross source boundary
r = preview([1, 2], [3, 4], 3) assert type(r) is list and r == [1, 2, 3]
- empty
r = preview([], [], 3) assert type(r) is list and r == []
- zero does not consume
a = iter([1, 2]) b = iter([3]) r = preview(a, b, 0) assert type(r) is list and r == [] assert next(a) == 1 and next(b) == 3
- one shot remainder
a = iter([1, 2]) b = iter([3, 4]) r = preview(a, b, 3) assert type(r) is list and r == [1, 2, 3] assert list(a) == [] and list(b) == [4]
- duplicates and short source
r = preview([2, 2], [2], 9) assert type(r) is list and r == [2, 2, 2] and all(type(x) is int for x in r)
- ownership
a, b = [1, 2], [3] r = preview(a, b, 2) s = preview(a, b, 2) assert type(r) is list and r == s == [1, 2] and r is not s and r is not a r.append(9) assert a == [1, 2] and b == [3] and s == [1, 2]
What does the memory bound actually cover?
The result holds at most limit references. Source objects may already be large, and nested items remain shared. Work is O(k) iterator steps for k returned items, not a promise about total source memory.
Guide: summarise adjacent runs
Return consecutive run lengths without globally regrouping values.
The contract
- Input is a finite iterable of strings. Return a fresh list of (string, integer) tuples in run order.
- Adjacent equal strings merge; separated equal strings stay separate. Empty input returns [].
- Consume one-shot inputs once. Do not sort or mutate source lists; output has a new outer list.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- separated repeats
r = run_lengths(['a', 'a', 'b', 'a']) assert type(r) is list and r == [('a', 2), ('b', 1), ('a', 1)] assert all(type(t) is tuple and type(t[0]) is str and type(t[1]) is int for t in r) - empty
r = run_lengths([]) assert type(r) is list and r == []
- all one run
r = run_lengths(['x'] * 4) assert type(r) is list and r == [('x', 4)] - alternating
r = run_lengths(['b', 'a', 'b', 'a']) assert type(r) is list and r == [('b', 1), ('a', 1), ('b', 1), ('a', 1)] - one-shot and empty labels
source = iter(['', '', 'x']) r = run_lengths(source) assert type(r) is list and r == [('', 2), ('x', 1)] assert list(source) == [] - fresh output and input preservation
source = ['z', 'z', 'a'] a = run_lengths(source) b = run_lengths(source) assert type(a) is list and a == b == [('z', 2), ('a', 1)] and a is not b a.clear() assert source == ['z', 'z', 'a'] and b == [('z', 2), ('a', 1)]
Why must the group be consumed inside the loop?
groupby groups share the underlying iterator. Advancing loses access to earlier unconsumed values. The one-pass count takes O(n) steps and O(r) result tuples for r runs.
Transfer: aggregate all labels, not runs
Change the requirement to global counts in first-seen order.
The contract
- Input is a finite iterable of strings. Return a fresh list of (label, integer count) tuples, one per distinct label.
- Merge nonadjacent repeats, preserving first-seen key order, not alphabetical order. Empty input returns [].
- Accept one-shot iterators, do not sort/mutate list inputs, and keep separate output lists across calls.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- nonadjacent totals
r = global_counts(['b', 'a', 'b']) assert type(r) is list and r == [('b', 2), ('a', 1)] assert all(type(t) is tuple and type(t[0]) is str and type(t[1]) is int for t in r) - empty
r = global_counts([]) assert type(r) is list and r == []
- all repeats
r = global_counts(['q', 'q', 'q']) assert type(r) is list and r == [('q', 3)] - first-seen order
r = global_counts(['z', 'b', 'a', 'b', 'z']) assert type(r) is list and r == [('z', 2), ('b', 2), ('a', 1)] - one-shot and empty label
source = iter(['', 'x', '']) r = global_counts(source) assert type(r) is list and r == [('', 2), ('x', 1)] and list(source) == [] - input and result ownership
source = ['y', 'x', 'y'] a = global_counts(source) b = global_counts(source) assert type(a) is list and a == b == [('y', 2), ('x', 1)] and a is not b a.append(('new', 1)) assert b == [('y', 2), ('x', 1)] and source == ['y', 'x', 'y']
Why is sorting plus groupby not an equivalent replacement?
It would change first-seen key order unless extra state restored it. A mapping meets global counting directly: expected O(n) hash-table work, O(d) retained counts and output for d distinct labels.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneCaching trades work for retention
A cache retains earlier results to avoid repeating work. It also retains arguments and return objects, so bounded size and ownership are part of its contract.
Understand first
Repeated deterministic calculations can reuse results instead of repeating work. Cache only when saved computation justifies retention and a stale result is not harmful. A calculation that depends on a clock or changing settings needs a freshness policy.
Words you will see
- Cache hit
- A call answered from a retained result.
- Cache miss
- A call that needs the underlying function to run.
- LRU
- Least recently used: the eviction policy for removing old entries when capacity is reached.
Count work separately from returned values
The first square(3) misses and computes 9. The second call hits and returns the retained 9. hits and misses therefore print 1 and 1. Calls for 4 and 5 add new keys; capacity two means an older entry must be evicted.
maxsize limits entry count, not the total bytes in keys and values. Arguments must be hashable. A dictionary or list argument is not directly usable as a cache key. Cache metadata describes this wrapper, not all memory in the program.
Do not share mutable results by accident
A cache returns the same retained result object for a matching key. If that object is a list, a caller's mutation may affect later callers. Return immutable values, make deliberate copies at the boundary, or document shared ownership.
functools.cache is unbounded, whereas lru_cache can have a finite capacity. Neither chooses a freshness policy for changing external data. For cheap square arithmetic, caching is usually unnecessary; this function is deliberately small so cache state can be inspected deterministically.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
@lru_cache(maxsize=2)Wrap the following function with a two-entry cache.
print(square(3), square(3))Perform one miss then one hit.
print(square.cache_info().hits, square.cache_info().misses)Display the wrapper's counters.
print(square.cache_info().currsize)Show that three distinct keys did not leave three retained entries.
functools.cache and lru_cache retain keys and results and require hashable arguments. Choose a bounded cache when input cardinality is not bounded. Caching time-dependent or mutable results without an invalidation policy can produce stale behaviour.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Change capacity.
Try: Set maxsize=3.
The final currsize becomes 3.
Clear retention explicitly.
Try: Add square.cache_clear() before the final print.
The final currsize becomes 0 and the wrapper's counters reset.
Before you move on
If a cached function returns [] and a caller appends to it, can the next call for that key see the change?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Yes. The cache retains and returns that list object. Caching does not copy or freeze it; choose an immutable result or a separate copy policy.
Clarity before cleverness
partial makes a callable with some arguments already chosen. wraps helps a wrapper retain the original function's descriptive metadata; neither tool changes what arguments mean.
Understand first
A callback may need a fixed prefix, and a decorator may need to add behaviour without obscuring documentation. These tools avoid small anonymous adapters when a named configured callable or an honest wrapper is clearer.
Words you will see
- partial
- A callable that supplies selected arguments to another callable.
- Wrapper
- A function that delegates to another function, often adding behaviour around the call.
- Metadata
- Descriptive attributes such as a function's name, documentation and wrapped reference.
Configuration does not execute the function yet
partial(label, prefix='WARN: ') records the target and a default keyword. Calling warn('retry') supplies value and produces WARN: retry. It does not compute a label when warn is constructed. A keyword supplied later can override a bound keyword, so partial is not an access-control boundary.
The traced decorator creates a wrapper accepting positional and keyword arguments. It forwards both sets unchanged. wraps copies useful metadata and establishes __wrapped__, so wrapped.__name__ is label even though a distinct wrapper function runs.
Choose a loop or explicit function when clearer
wraps does not automatically forward arguments or preserve runtime behaviour; the body must do that. A wrapper that forgets return would return None regardless of metadata. partial retains references to bound values, so mutable configuration is not frozen by binding it.
These examples do not add real logging, timing or asynchronous work. For a complicated adapter with validation, a normal named function may explain its contract better. Use functional tools to expose a simple transformation, not to hide state or exception handling.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
warn = partial(label, prefix='WARN: ')Bind the prefix without calling label yet.
@wraps(function)Copy descriptive metadata onto the new wrapper.
return function(*args, **kwargs)Preserve the actual returned value and forward arguments.
print(wrapped.__name__)Show label rather than wrapper as the descriptive name.
partial can configure a function without hiding its remaining parameters. wraps preserves wrapper metadata. Prefer a simple loop when a chain of combinators makes exception handling or intermediate state harder to understand.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Override configuration.
Try: Replace warn('retry') with warn('retry', prefix='INFO: ').
The first output becomes INFO: retry.
Observe metadata without wraps.
Try: Remove the @wraps(function) line.
The result strings stay the same but wrapped.__name__ becomes wrapper.
Before you move on
What happens if warn('go', prefix='NOTE: ') is called with this partial?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
It returns 'NOTE: go'. The call-time keyword overrides the stored keyword. partial is configuration convenience, not a rule forbidding overrides.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.