Interview bank: design and language depth
A structured rehearsal with model explanations, evaluation signals and follow-up constraints. These are original representative questions, not a claimed company interview bank.
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: 30 minutes; optional deep dive: 20 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 reasoning before implementation
- Identify assumptions and edge cases
- Assess an answer against explicit signals
Interview rehearsal
30-minute suggested practice budget. No automatic timer or grading. Answer first, then compare the explanation and evaluation signals.
Common representative Python interview themes, not a measured frequency ranking or a claim about a particular company.
1. Build a typed decorator that preserves an arbitrary callable's parameter types, return type, name, and inspectable signature.
Reveal answer and evaluation signals
Use ParamSpec for the forwarded parameter specification and a TypeVar for the return type. functools.wraps preserves runtime metadata and exposes __wrapped__, which inspect.signature normally follows. These mechanisms complement each other: wraps does not supply static type preservation, and type annotations do not perform runtime argument validation.
How it works
ParamSpec expresses the relationship between the input callable's parameters and the wrapper's *args and **kwargs. A return TypeVar links the wrapper result to the original result. At runtime, wraps copies selected attributes and installs an unwrapping link; introspection can follow that link instead of displaying only the generic forwarding signature.
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.
When to choose it and what it costs
Use this pattern for behavior-preserving instrumentation. If the wrapper changes accepted arguments or return shape, describe that changed contract rather than copying an inaccurate signature. Test integration with frameworks that inspect callables instead of assuming metadata alone guarantees compatibility.
Pitfalls and edge cases
- Callable[..., R] discards parameter relationships and weakens useful checking.
- wraps cannot make a synchronous wrapper behave like an async function.
- Uses ParamSpec and return TypeVar
- Preserves metadata with wraps
- Separates typing from enforcement
Follow-up: What changes if the decorator adds a leading dependency parameter?
Concatenate can describe a callable with an added leading parameter and ParamSpec for the remainder. Decide whether callers supply the dependency or the decorator injects it, because those choices produce opposite public signature transformations.
Interview-ready takeaway
Typed forwarding and runtime metadata solve different problems; preserve each deliberately and represent any signature transformation honestly.
2. Why does a property override a same-named entry in an instance dictionary, while a normal method can be shadowed there?
Reveal answer and evaluation signals
Properties are data descriptors and take precedence over instance dictionary entries. Ordinary functions on a class implement descriptor binding but are non-data descriptors, so an instance attribute can shadow them. Attribute lookup considers descriptors, instance storage, and the class hierarchy in a defined precedence rather than simply checking the instance first.
How it works
For ordinary object lookup, Python searches the class MRO for an attribute. A data descriptor with __set__ or __delete__ wins before instance storage; otherwise the instance dictionary can win before a non-data descriptor is bound. Functions implement __get__ to produce bound methods. __getattr__ is a fallback after normal lookup fails.
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.
When to choose it and what it costs
Use a property when attribute syntax should enforce a computed or validated contract. Use a reusable descriptor for the same behavior across many fields. Avoid overriding __getattribute__ unless necessary because it affects every access and makes ordinary lookup assumptions harder to maintain.
Pitfalls and edge cases
- Accessing self.attribute inside its own lookup hook can recurse indefinitely.
- Properties can execute arbitrary code, so attribute access is not necessarily cheap or side-effect-free.
- Explains data versus non-data descriptors
- Describes lookup precedence
- Recognizes method binding
Follow-up: Does a property without a setter still count as a data descriptor?
Yes. property provides descriptor assignment behavior even when its setter is absent; the attempted assignment raises AttributeError. That is why inserting a value into __dict__ does not override the property in normal lookup.
Interview-ready takeaway
Descriptor category determines precedence. Understanding data descriptors explains properties, method binding, validation, and several surprising shadowing behaviors.
3. In a diamond inheritance hierarchy, why is super() not simply 'call my parent', and how can cooperative initialization work?
Reveal answer and evaluation signals
super() continues lookup after a particular class in the current instance's method resolution order. In a diamond, that next class may be a sibling in the graph rather than a directly named parent. Cooperative methods call super consistently and agree on compatible signatures so each participant can execute once.
How it works
Python uses C3 linearization to produce a consistent MRO preserving local ordering constraints. Zero-argument super uses the defining class and the current first argument to continue that order. Hard-coding a base class call bypasses the cooperative chain and can skip behavior or run a shared ancestor more than once.
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.
When to choose it and what it costs
Use cooperative inheritance for a controlled family of orthogonal behaviors with documented conventions. For initialization, consume owned keyword arguments and forward supported remaining arguments consistently. Prefer composition when dependencies have independent lifecycles or when ordering mixins materially changes business meaning.
Pitfalls and edge cases
- Mixing direct base calls with super can duplicate initialization.
- Incompatible method signatures can break a chain even when each class works independently.
- Uses MRO continuation model
- Explains cooperative chain
- Knows when composition is simpler
Follow-up: When would composition be preferable to another mixin?
Choose composition when behavior should be replaceable independently, needs explicit dependencies, or is not genuinely a substitutable subtype relationship. Delegating to a collaborator makes ordering and state ownership visible without relying on MRO-sensitive interactions.
Interview-ready takeaway
super follows the runtime MRO, not a single parent edge. Cooperative contracts are essential; composition avoids many inheritance-order dependencies.
4. Does a frozen slotted dataclass make an immutable, automatically hashable value object in every case?
Reveal answer and evaluation signals
No. frozen prevents ordinary field rebinding, not mutation inside referenced objects. slots restricts normal instance storage but is not a security or universal memory guarantee. A frozen dataclass with generated equality normally receives a generated hash, but hashing still fails if a participating field is unhashable.
How it works
dataclass generates methods from annotated fields and configuration. Frozen assignment guards raise FrozenInstanceError, while generated equality compares relevant fields. A generated hash combines participating field hashes. Slots define declared storage and generally remove a per-instance dictionary unless inherited structure provides one; they do not recursively freeze any field values.
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.
When to choose it and what it costs
Use tuples or frozensets of immutable values for fields participating in value identity. Exclude derived caches from comparison and hashing when appropriate. Select slots after measuring representative allocations and considering weak references, inheritance, debugging, and serialization requirements.
Pitfalls and edge cases
- unsafe_hash=True does not make mutable identity safe as a dictionary key.
- Frozen is an API discipline rather than a defense against deliberately bypassing assignment guards.
- Distinguishes shallow frozen behavior
- Explains slots constraints
- Checks hashable fields
Follow-up: How should a collection-valued field be represented in a hashable record?
Use a tuple when order and duplicates matter, or a frozenset when membership alone defines identity. Validate or normalize the input at construction so callers cannot retain a mutable list that changes the record's logical value.
Interview-ready takeaway
Frozen, slotted, immutable, and hashable describe different properties. Design field ownership and identity before selecting dataclass options.
5. How can a function accept any object with a read method without requiring inheritance, and what can a runtime-checkable Protocol actually prove?
Reveal answer and evaluation signals
A Protocol expresses structural compatibility: an object can satisfy it by providing the required operations without inheriting from it. Static checking can verify compatible method signatures. runtime_checkable permits limited runtime checks for required members, but does not validate detailed signatures, return types, or behavioral correctness.
How it works
Typing protocols describe capabilities rather than nominal ancestry. Generic TypeVars connect types across a signature, allowing a checker to infer a concrete result type from an argument. Runtime Python still executes ordinary attribute lookup and calls; annotations generally do not wrap objects or enforce a protocol at each invocation.
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.
When to choose it and what it costs
Use small capability protocols for collaborators in libraries and tests. Prefer an abstract base class when shared implementation or explicit registration is the requirement. At untrusted boundaries, perform concrete data validation instead of treating a protocol check as schema verification.
Pitfalls and edge cases
- A matching attribute name can pass a runtime check while having an incompatible callable signature.
- An empty sequence still causes first to raise IndexError despite correct generic annotations.
- Explains structural typing
- Separates static and runtime checks
- Uses generics to preserve relationships
Follow-up: How would you keep a helper's returned item type related to its input sequence type?
Use a TypeVar in both Sequence[T] and the return annotation. Decide separately how an empty sequence behaves: raise a documented error, return an optional result, or require a nonempty domain object.
Interview-ready takeaway
Protocols express capabilities and generics express type relationships. Neither replaces runtime validation or a behavioral contract.
6. A generator-based context manager must release a resource when the body raises. Where should try/finally surround yield?
Reveal answer and evaluation signals
Acquire before yielding, place yield inside try, and release in finally. The contextmanager machinery resumes the generator after the body or injects the body's exception at yield. The generator should yield exactly once. Cleanup should not accidentally swallow exceptions or replace the body failure with an unrelated return policy.
How it works
contextlib.contextmanager adapts a generator to the context-manager protocol. Entry advances to the yield, whose value becomes the as target. Exit resumes or throws into the generator. A finally block therefore covers both ordinary completion and a failure in the managed body after successful entry.
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.
When to choose it and what it costs
Use a generator context manager for a straightforward acquire-use-release lifecycle. A dedicated class can be clearer for reusable state, multiple methods, or complex entry failure handling. Keep acquisition failure cleanup inside the acquisition logic because exit is not called if entry never succeeds.
Pitfalls and edge cases
- Catching the injected exception and not re-raising can unintentionally suppress the body failure.
- A second yield violates the contextmanager protocol rather than providing a second managed phase.
- Places cleanup in finally
- Explains exception injection
- Requires exactly one yield
Follow-up: How would you manage a dynamic number of resources safely?
Use ExitStack to enter resources as they are discovered and register callbacks immediately after successful acquisition. If later acquisition fails, already registered resources are released in reverse order without deeply nested with statements.
Interview-ready takeaway
The yield is the lifetime boundary. Protect it with finally and use ExitStack for dynamic, exception-safe reverse-order cleanup.
7. A custom key becomes unreachable in a dictionary after one field changes. What equality and hashing contract was broken?
Reveal answer and evaluation signals
Equal objects must have equal hashes, and a key's hash must remain stable while it is stored in a hash collection. If mutable fields determine the hash or equality, changing them can strand the entry in a bucket selected by its old hash. Use immutable identity or a separate immutable key.
How it works
A dictionary uses a key's hash to locate candidate entries and equality to distinguish collisions. Hashes need not be unique. Python normally disables inherited hashing when a class defines value equality without a corresponding hash, preventing accidental use of incompatible identity-based hashing for objects that compare equal by value.
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.
When to choose it and what it costs
Define whether an entity's identity is a permanent identifier or its full value. Database-like entities often need an immutable identifier key even when other fields change. Value objects can include all immutable identity fields in both equality and hashing.
Pitfalls and edge cases
- Returning a constant hash is legal but can degrade performance through collisions.
- Excluding a mutable field from hash while retaining it in equality still allows key meaning to change after insertion.
- States equality/hash invariant
- Explains mutation hazard
- Avoids claiming unique hashes
Follow-up: Why is a class that defines __eq__ often unhashable unless it also defines __hash__?
Object's default hash corresponds to identity semantics, which may conflict with newly defined value equality. Setting __hash__ to None forces the author to make an explicit consistent choice rather than silently violating equal-objects-equal-hashes.
Interview-ready takeaway
Hashing locates candidates and equality resolves them. Stable immutable key identity matters more than clever hash formulas.
8. How would you organize a small reusable package so importing it is safe, its command can be tested, and installation does not depend on the working directory?
Reveal answer and evaluation signals
Separate reusable functions from the command entry point, declare build and project metadata in pyproject.toml, and test the installed package rather than relying solely on source-tree imports. Avoid changing sys.path inside application code. Keep import-time work lightweight and pass dependencies explicitly to the command.
How it works
Python resolves imports through its configured import machinery and search paths. Running tests beside the repository can accidentally import local source even when the built distribution omits files. A src layout reduces that accidental success, while testing a wheel in a clean environment exercises the files and metadata actually shipped.
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.
When to choose it and what it costs
Use a documented console entry point for installed commands and a small main function for testability. Declare supported Python versions and optional dependencies explicitly. Add an installation smoke test that imports the public API and runs the command from outside the repository.
Pitfalls and edge cases
- Editable installs can hide missing wheel contents or undeclared dependencies.
- Importing a module should not parse the process command line or launch application work.
- Separates library and command
- Describes installation metadata
- Tests installed artifacts
Follow-up: What does a src layout prevent, and what does it not guarantee?
It makes uninstalled source less likely to be importable accidentally from the repository root. It does not prove that metadata, package data, dependencies, or entry points are correct; a built-artifact test is still needed.
Interview-ready takeaway
Packaging is a distribution contract, not just a folder structure. Isolate command behavior and test what users actually install.
9. A unit test patches a function in its defining module, yet the code under test still calls the original. Where should the patch be applied?
Reveal answer and evaluation signals
Patch the name where the code under test looks it up. A from-module import binds a reference in the importing module, so later replacing the defining module's attribute does not change that local reference. Prefer explicit dependency injection when possible, and use autospec to reduce mock interface drift.
How it works
Importing a function into another namespace copies a reference binding, not a live link to the original attribute. patch temporarily replaces an attribute and restores it on exit. autospec can mirror a callable's signature, but a mock still does not implement its actual protocol, data semantics, or failure behavior.
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.
When to choose it and what it costs
Mock expensive or nondeterministic boundaries in focused unit tests, then retain contract tests against real adapters using safe local fixtures. Assert outcomes and important interactions rather than every internal call, so tests allow implementation refactoring.
Pitfalls and edge cases
- An unconstrained mock can accept misspelled methods and impossible argument combinations.
- A test can accidentally exercise its own invented behavior rather than the production dependency contract.
- Patches lookup namespace
- Understands imported bindings
- Combines mocks with real integration tests
Follow-up: Why can an all-mock test suite pass while production fails?
Mocks can return unrealistic shapes, omit failure modes, and drift from real APIs. Add integration or contract tests for serialization, errors, and boundary behavior, and use recorded synthetic fixtures rather than production credentials or personal data.
Interview-ready takeaway
Patch the consumer's lookup location and keep mocks honest with interface constraints and independent boundary tests.
10. JSON parsing succeeds for a payload with an extra field and a boolean count. Has schema validation succeeded?
Reveal answer and evaluation signals
No. JSON parsing establishes syntactic validity and produces Python values; it does not enforce the application's schema. Define required fields, unknown-field policy, accepted types, bounds, and versioning separately. Because bool is an int subclass, exact numeric schema rules may need a stricter check than isinstance(value, int).
How it works
json.loads maps JSON objects and arrays to dictionaries and lists. Those values can be structurally valid but semantically unacceptable. Validation should construct a trusted internal representation only after checking shape and meaning. Duplicate object names and nonstandard numeric constants also require a deliberate acceptance policy when the protocol demands strictness.
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.
When to choose it and what it costs
For a small schema, explicit standard-library checks can be clear. For evolving complex contracts, use a maintained schema system in the actual application and test its coercion settings. Keep wire validation separate from domain rules requiring other trusted state.
Pitfalls and edge cases
- Automatic coercion can make invalid input appear valid unless the contract explicitly allows it.
- A parsed object is not automatically safe to pass to SQL, templates, or other interpreters.
- Separates syntax and schema
- Validates unknown keys and exact types
- Plans size and nesting limits
Follow-up: What limits should exist before and after parsing untrusted JSON?
Bound request bytes before parsing, and constrain nesting, collection sizes, strings, numeric ranges, and validation work. Reject unsupported schema versions and define duplicate-key behavior. Parser success alone does not bound resource use or establish authorization.
Interview-ready takeaway
Syntax acceptance is only the first boundary. Schema, domain validity, resource budgets, and downstream interpretation need independent controls.
11. A recursive computation uses lru_cache. What makes a cache key correct, and which behaviors should tests cover besides a cache hit?
Reveal answer and evaluation signals
The key must include every input that determines the result, and those inputs must be hashable. Hidden mutable configuration can make cached results stale. Bound the cache unless the key space is provably limited, define invalidation, and test eviction, misses, failure behavior, and interactions with mutable returned values.
How it works
lru_cache retains arguments and results in a bounded least-recently-used structure. Equivalent calls reuse a stored result under its keying rules; distinct argument patterns may create separate entries. Cached objects remain referenced until eviction or clearing. Thread-safe cache bookkeeping does not necessarily serialize execution of the wrapped function for the same missing key.
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.
When to choose it and what it costs
Cache pure expensive computations whose repeated inputs are common enough to justify retention. For data that changes externally, include a version or use a defined expiration and invalidation policy. Measure hit rate and retained size rather than assuming a cache is always an optimization.
Pitfalls and edge cases
- Returning a mutable list allows one caller to modify the value later callers receive.
- Caching bound methods can retain instances through references in keys.
- Includes semantic inputs in key
- Bounds retention
- Avoids shared mutable result surprises
Follow-up: Does lru_cache guarantee that concurrent callers compute a missing value only once?
No. More than one caller can execute the wrapped function before the first result is stored. If duplicate work or side effects are unacceptable, implement an explicit single-flight mechanism and define failure and cancellation behavior.
Interview-ready takeaway
A cache is retained shared state with a key, lifetime, and concurrency contract; test those contracts as carefully as the computation.
12. Why are __getattribute__ and __getattr__ not interchangeable, and how can a proxy expose a helpful fallback without breaking normal attributes?
Reveal answer and evaluation signals
__getattribute__ participates in every ordinary attribute access, while __getattr__ is a fallback after normal lookup raises AttributeError. A proxy can usually implement __getattr__ to delegate unknown names while leaving its own methods and stored attributes alone. Overriding all lookup requires careful use of object.__getattribute__ to avoid recursion.
How it works
Normal attribute lookup consults the class hierarchy, descriptor rules, and instance storage. If that path ends in AttributeError, __getattr__ can supply a value. Many implicit special operations resolve methods on the type rather than performing the same ordinary instance lookup, so a generic fallback does not implement every language protocol.
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.
When to choose it and what it costs
Keep delegation narrow and explicit when the public interface is small. A universal transparent proxy must handle special methods, identity, lifetime, descriptors, and error semantics, making it substantially more complex than forwarding unknown names.
Pitfalls and edge cases
- Returning None for every unknown name makes hasattr misleadingly report success.
- A property raising AttributeError internally can trigger fallback and conceal the original defect.
- Distinguishes primary lookup and fallback
- Avoids recursion
- Recognizes special-method lookup limits
Follow-up: Will __getattr__ delegation alone make len(proxy) behave like len(target)?
No. Define __len__ on the proxy's class and delegate deliberately if that protocol is required. Similar care applies to arithmetic, iteration, context management, and other implicit special-method operations.
Interview-ready takeaway
Fallback lookup is useful delegation, not universal transparency. Preserve AttributeError and implement required language protocols explicitly.
13. A function needs a local copy but accepts any Iterable[int]. How do iterator semantics, typing, and complexity shape its API?
Reveal answer and evaluation signals
An Iterable may be a reusable collection or a single-pass source. Converting it to a list consumes it and allocates storage proportional to its length. If the algorithm needs indexing and repeated passes, accept a Sequence or explicitly document materialization. A generic Iterable annotation does not promise finiteness or cheap iteration.
How it works
Iterable promises that iter(value) can provide an iterator. It does not promise len, indexing, restartability, or a bounded number of values. Sequence expresses additional operations but still does not necessarily promise constant-time indexing for every implementation. Type annotations capture capabilities, while runtime complexity and resource limits remain documented behavioral contracts.
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.
When to choose it and what it costs
Accept the weakest capability the algorithm genuinely needs, but do not obscure important requirements such as finite length or repeatable traversal. For streaming interfaces, expose bounds and ownership of the cursor so callers can predict consumption.
Pitfalls and edge cases
- list(values) on an unbounded source never reaches a usable result and can exhaust memory.
- Calling iter twice is not two independent passes when values is already an iterator.
- Identifies consumption and allocation
- Selects minimal honest capability
- Defines finite-input requirement
Follow-up: When is itertools.islice preferable to ordinary slicing?
Use islice for incremental forward selection from iterables without constructing a full source list. It consumes skipped elements and does not support negative indices like a sequence slice, so the two APIs are not interchangeable.
Interview-ready takeaway
Iterable is a capability, not a resource guarantee. State finiteness, consumption, indexing needs, and allocation behavior separately.
14. How would you test a batching helper beyond three hand-picked examples without adding a third-party property-testing package?
Reveal answer and evaluation signals
Express invariants and test them across a bounded systematic input space. For batching, concatenating batches should reconstruct the input, order must be preserved, every nonfinal batch should have the requested size, and invalid sizes should fail explicitly. Include empty input and sizes larger than the input.
How it works
An invariant describes a relationship that should hold for many inputs instead of listing one expected output. Small exhaustive loops can explore boundary combinations deterministically. Independent assertions about reconstruction and batch lengths catch different bugs; repeating the implementation's own slicing logic as the oracle would provide much weaker evidence.
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.
When to choose it and what it costs
Combine invariant tests with readable examples explaining important business expectations. Use targeted regression cases for known defects and integration tests for boundaries the helper does not model. Avoid enormous exhaustive ranges that slow feedback without exploring meaningfully different behavior.
Pitfalls and edge cases
- Coverage only establishes that lines ran, not that outcomes were checked correctly.
- Random tests without recorded seeds or shrinking can be difficult to reproduce.
- Defines invariants
- Exercises bounded edge space
- Avoids using implementation as oracle
Follow-up: What makes a useful regression test different from merely increasing line coverage?
A regression test reproduces the failure condition and asserts the intended behavior independently enough to fail before the fix. Coverage can guide missing paths, but a test that executes code without meaningful assertions does not protect its contract.
Interview-ready takeaway
Test relationships, boundaries, and documented failures. Bounded systematic invariants provide strong deterministic evidence without requiring extra tooling.
15. When should an object implement __iter__ by returning a fresh iterator instead of implementing __next__ itself?
Reveal answer and evaluation signals
A reusable collection should normally return a new independent iterator for each traversal. An iterator is its own traversal state and usually returns itself from __iter__. Combining collection storage and one shared cursor can make nested loops and repeated passes interfere, even though a simple first traversal appears correct.
How it works
for calls iter to obtain a cursor, then repeatedly calls next on that cursor. A collection can retain immutable storage while each iterator retains its own position. A generator-based __iter__ creates a new generator object on every call, naturally separating cursor state without making the collection itself an 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.
When to choose it and what it costs
Use an iterator object for a genuine one-pass stream whose progress is meaningful state. Use an iterable collection for stored data that callers should traverse independently. Document whether changes to underlying storage are reflected or rejected during an active traversal.
Pitfalls and edge cases
- Returning self without implementing __next__ does not create a valid iterator.
- Fresh iterators do not automatically provide a snapshot if they read concurrently mutable storage.
- Separates collection from cursor
- Supports independent nested iteration
- Explains iterator exhaustion
Follow-up: Can a generator method implement a reusable collection's __iter__?
Yes. Each call creates a fresh generator with its own execution state. Capturing a tuple in construction also stabilizes this example's storage. For live collections, choose explicitly whether each iterator sees a snapshot or ongoing changes.
Interview-ready takeaway
Collections own values and iterators own positions. Keeping those roles separate enables predictable repeated and nested traversal.
Run an honest rehearsal
An intermediate design answer separates parsing a representation from validating the application's contract. Valid JSON can still describe invalid work.
Understand first
A boolean can pass an isinstance(value, int) check in Python. Extra fields can hide an incompatible request even when parsing succeeds.
Words you will see
- Schema
- The permitted fields and value rules of a message.
- Exact type
- The concrete type, tested with type(value) is T.
- Validation boundary
- The point where external data becomes accepted domain data.
Validate shape before meaning
The sample uses already parsed dictionaries. set(payload) checks exactly the required field names. The count rule uses type(...) is int, excluding bool even though bool is a subclass of int. The lower bound separately rejects negative counts.
Order the tests so missing or extra keys stop the expression before count lookup. This is safe because and short-circuits. Parsing JSON alone says nothing about these application rules, and annotations alone do not enforce them.
State the remaining constraints
This small example validates count only; it is not a complete job schema. A real job also needs the name rule, size limits and a policy for unknown fields. Decide whether to reject extras or preserve forward-compatible fields rather than silently accepting them.
For k fields, constructing a set of keys takes O(k) time and extra space under ordinary hash behaviour. Do not claim validation is constant time for unbounded input. Reject an oversized transport body before allocating its complete decoded form.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def valid(payload):Accept a parsed dictionary, not arbitrary serialized input.
set(payload) == {"count"}Require exactly one known field before accessing it.
and type(payload["count"]) is intReject booleans despite their integer subclass relationship.
and payload["count"] >= 0Enforce the domain bound after the type check.
Answer without the model response first. State your assumptions, give a small example and discuss an edge case. The suggested time is a practice budget, not an automatic timer, proctoring claim or hiring-readiness prediction.
Conceptual validation boundary, not a security certification
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- RepresentationA parser creates Python objects.
- Shape and typesRequire known fields and an exact integer count.
- DomainReject negative counts before accepting the 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.
Change one thing; explain the difference.
Test the lower boundary.
Try: Add {'count': 0} to the tuple.
The new result is True; zero is valid, not missing.
Loosen the numeric test.
Try: Replace type(payload['count']) is int with isinstance(payload['count'], int).
The boolean case now passes, exposing the changed contract.
Before you move on
Would {'count': 0} satisfy this contract, and would {'count': '0'}?
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
The integer zero is accepted. The string is rejected; this boundary does not promise coercion. Any coercion should be a separate explicit rule.
Use the rubric, not keyword matching
A reusable iterable can return a fresh iterator each time. A one-shot iterator returns its own advancing state instead.
Understand first
Accepting Iterable[int] does not promise that two traversals see the same data. A design must say whether it consumes input or saves it.
Words you will see
- Iterable
- An object from which iter can obtain an iterator.
- One-shot source
- A source whose already consumed values cannot be replayed automatically.
- Materialisation
- Collecting a stream into a stored container.
Compare the two APIs
Calling list(values) twice on the list creates fresh iterators and reproduces all three values. Calling list(stream) consumes the existing iterator; calling again returns no values. Both objects are iterable, but only one is reusable this way.
A function needing two passes can materialise once at its boundary. It should not silently assume that an Iterable is a Sequence with len or indexing. A generator may be finite, huge or infinite; state the accepted bound.
Explain ownership and costs
list(stream) allocates new outer storage while sharing its elements. For a finite source of n entries, it takes O(n) time and O(n) extra reference slots. A streaming batching API can retain only a bounded block, but a function returning every block still stores O(n) output.
Annotations describe accepted operations to tooling; they do not prove purity or prevent consumption at runtime. Test a list and a generator with the same values. Include an empty source and a final partial batch when the requirement is batching.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
values = [2, 4, 6]Build reusable storage.
stream = iter(values)Create one cursor into that storage.
print(list(values))Obtain a fresh iterator from the list for each call.
print(list(stream))Consume the cursor; the repeated line later observes exhaustion.
An answer can be correct without matching the model wording. Evaluate whether the reasoning establishes the contract and handles follow-ups. A self-rating or revealed answer must not become an independently judged coding pass.
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.
Obtain a fresh cursor.
Try: Insert stream = iter(values) before the final print.
The final line now prints all three values.
Use no values.
Try: Set values = [].
All four prints are empty lists; emptiness does not distinguish replay from exhaustion.
Before you move on
How can a function compute both a minimum and a maximum from one finite generator without losing its first traversal?
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
Either update both in one pass, handling empty input explicitly, or materialise once and use that saved list. Two independent traversals of the same exhausted iterator will not work.
Static and runtime transparency
A transparent decorator preserves both the callable's behaviour and the information tools use to describe it. Static forwarding types and runtime metadata solve different problems.
Understand first
The original bank example must accept the keyword-only loud option, return the actual greeting and retain the original name and inspectable parameters.
Words you will see
- ParamSpec
- A typing variable that relates a callable's parameter list to a wrapper.
- TypeVar
- A typing variable linking input and output types.
- Unwrapping link
- The __wrapped__ reference that lets tools inspect the original callable.
Follow the original call
identity_wrapper receives greet and builds wrapper. The wrapper accepts positional and named arguments, forwards them unchanged and returns the result. Calling greet with loud=True therefore returns ADA rather than None.
wraps copies selected metadata and sets __wrapped__. inspect.signature normally follows that link, so its parameter names are name and loud instead of args and kwargs. The stored annotations relate forwarding types to a checker; Python does not automatically reject a bad value at runtime.
Choose honest transparency
A wrapper that adds or removes arguments needs a different public contract, possibly expressed with Concatenate. Merely copying metadata can make an intentionally changed API misleading. Test behaviour and signature separately.
The wrapper adds one call layer; the wrapped function still determines most work and allocation. It returns the original result, not a copy. A synchronous wrapper does not become an async coroutine function just because wraps copied metadata.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
P = ParamSpec("P")Describe the forwarded parameter relationship for static tooling.
@wraps(function)Copy runtime metadata and install the unwrapping link.
return function(*args, **kwargs)Forward the call and preserve its actual returned object.
print(tuple(signature(greet).parameters))Observe the original name and keyword-only option through introspection.
The call exercises a keyword-only option, while name and signature checks cover runtime tooling. The annotations describe forwarding to a type checker but do not alter the callable's execution or reject values on their own.
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.
Test the default branch.
Try: Change greet('Ada', loud=True) to greet('Ada').
The greeting is Ada while name and signature stay unchanged.
Remove runtime metadata preservation.
Try: Delete @wraps(function).
The value remains ADA, but the name becomes wrapper and the visible parameters become args and kwargs.
Before you move on
If the wrapper calls function but omits return, which sample observation changes first?
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
The first print becomes None because the wrapper discards ADA. Name and signature can still look correct, showing why metadata tests alone are insufficient.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Explain and implement
Predict the worked example before running it locally, then change one boundary input and explain the result without the reference.
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.
Guided: preserve a callable's contract
Write a forwarding decorator that preserves the actual returned object, metadata and inspectable signature.
The contract
- Accept an ordinary synchronous callable. Forward positional and named arguments unchanged and return the exact object it returns.
- Preserve __name__, __doc__, __wrapped__ and inspect.signature behaviour with functools.wraps.
- Do not mutate caller-owned arguments or turn exceptions into success. This task does not promise async-function transparency or runtime type enforcement.
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.
- positional forwarding
from copy import deepcopy source = [1, 2] before = deepcopy(source) result = transparent(lambda values: list(values))(source) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [1, 2] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" wrapped = transparent(lambda values: values) assert callable(wrapped), "Decorator must return a callable" assert wrapped(source) is source, "Decorator must preserve exact result identity" assert source == before, "Decorator changed caller input" - empty forwarding
from copy import deepcopy source = [] before = deepcopy(source) result = transparent(lambda values: list(values))(source) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" wrapped = transparent(lambda values: values) assert callable(wrapped), "Decorator must return a callable" assert wrapped(source) is source, "Decorator must preserve exact result identity" assert source == before, "Decorator changed caller input" - keyword-only forwarding
from copy import deepcopy source = [2, 2] before = deepcopy(source) result = transparent(lambda values, *, extra: values + [extra])(source, extra=5) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [2, 2, 5] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" wrapped = transparent(lambda values: values) assert callable(wrapped), "Decorator must return a callable" assert wrapped(source) is source, "Decorator must preserve exact result identity" assert source == before, "Decorator changed caller input" - metadata and signature
from copy import deepcopy source = [3] before = deepcopy(source) result = transparent(lambda values: values[:])(source) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [3] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" wrapped = transparent(lambda values: values) assert callable(wrapped), "Decorator must return a callable" assert wrapped(source) is source, "Decorator must preserve exact result identity" assert source == before, "Decorator changed caller input" from inspect import signature def sample(values, *, option=1): 'Original documentation.' return values wrapped = transparent(sample) assert wrapped.__name__ == sample.__name__ and wrapped.__doc__ == sample.__doc__, 'Metadata lost' assert wrapped.__wrapped__ is sample and signature(wrapped) == signature(sample), 'Signature lost' assert wrapped(source) is source, 'Wrapper copied the returned object' - exceptions propagate
from copy import deepcopy source = [0] before = deepcopy(source) result = transparent(lambda values: values[:])(source) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [0] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" wrapped = transparent(lambda values: values) assert callable(wrapped), "Decorator must return a callable" assert wrapped(source) is source, "Decorator must preserve exact result identity" assert source == before, "Decorator changed caller input" def fail(values): raise ValueError('original failure') try: transparent(fail)(source) except ValueError as error: assert str(error) == 'original failure' else: assert False, 'Wrapper swallowed exception' - positional-only callable
from copy import deepcopy source = [-1, 4] before = deepcopy(source) result = transparent(lambda values, /: values[:])(source) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [-1, 4] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" wrapped = transparent(lambda values: values) assert callable(wrapped), "Decorator must return a callable" assert wrapped(source) is source, "Decorator must preserve exact result identity" assert source == before, "Decorator changed caller input"
Do wraps and ParamSpec do the same job?
No. wraps preserves runtime metadata and an unwrapping link; ParamSpec relates static parameter types. Forwarding adds a call layer and must not copy the return object or claim runtime validation.
Guided: validate a parsed job message
Reject extra fields and bool-as-int while preserving a valid zero count.
The contract
- payload is a parsed dictionary. Accept exactly keys name and count, a nonempty str name, and a nonnegative exact int count.
- Return (True, (name, count)) for valid input, otherwise (False, None); do not coerce strings, strip names or accept bool counts.
- Do not mutate the input. This is an offline schema exercise, not transport-size enforcement or a security certification.
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.
- normal
from copy import deepcopy source = {'name': 'build', 'count': 2} before = deepcopy(source) result = job_boundary(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (True, ('build', 2)) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool, "Validity must be a bool" assert result[1] is None or type(result[1]) is tuple, "Accepted data must be an immutable pair" - empty
from copy import deepcopy source = {} before = deepcopy(source) result = job_boundary(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (False, None) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool, "Validity must be a bool" assert result[1] is None or type(result[1]) is tuple, "Accepted data must be an immutable pair" - zero valid
from copy import deepcopy source = {'name': 'idle', 'count': 0} before = deepcopy(source) result = job_boundary(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (True, ('idle', 0)) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool, "Validity must be a bool" assert result[1] is None or type(result[1]) is tuple, "Accepted data must be an immutable pair" - boolean rejected
from copy import deepcopy source = {'name': 'build', 'count': True} before = deepcopy(source) result = job_boundary(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (False, None) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool, "Validity must be a bool" assert result[1] is None or type(result[1]) is tuple, "Accepted data must be an immutable pair" - extra field
from copy import deepcopy source = {'name': 'build', 'count': 2, 'extra': 1} before = deepcopy(source) result = job_boundary(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (False, None) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool, "Validity must be a bool" assert result[1] is None or type(result[1]) is tuple, "Accepted data must be an immutable pair" - invalid value boundaries
from copy import deepcopy source = {'name': '', 'count': -1} before = deepcopy(source) result = job_boundary(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (False, None) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool, "Validity must be a bool" assert result[1] is None or type(result[1]) is tuple, "Accepted data must be an immutable pair" for invalid in ({'name': '', 'count': 1}, {'name': 7, 'count': 1}, {'name': 'x', 'count': -1}, {'name': 'x', 'count': '2'}, {'name': 'x'}): assert job_boundary(invalid) == (False, None), 'A schema boundary was accepted'
What did JSON parsing fail to prove?
It did not prove exact fields, domain bounds or exclusion of boolean counts. Validation is separate; scanning k supplied keys costs O(k) ordinary hash work and extra key-set storage.
Transfer: batch a one-shot iterable
Accept a finite iterable, not just an indexable list. Keep the final partial batch and preserve every value exactly once.
The contract
- values is a finite iterable of integers and size is a positive exact integer.
- Return a new list of new nonempty lists, each at most size long; only the last may be partial. [] returns [].
- Consume a supplied iterator once without replaying it. Never mutate a source list or share returned row objects.
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.
- generator partial
from copy import deepcopy source = [1, 2, 3, 4, 5] before = deepcopy(source) result = batches((value for value in source), 2) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[1, 2], [3, 4], [5]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(type(row) is list for row in result), "Batches must be lists" assert len({id(row) for row in result}) == len(result), "Batches share storage" - empty
from copy import deepcopy source = [] before = deepcopy(source) result = batches(iter(source), 3) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(type(row) is list for row in result), "Batches must be lists" assert len({id(row) for row in result}) == len(result), "Batches share storage" - unit batches
from copy import deepcopy source = [2, 2, 0] before = deepcopy(source) result = batches(iter(source), 1) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[2], [2], [0]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(type(row) is list for row in result), "Batches must be lists" assert len({id(row) for row in result}) == len(result), "Batches share storage" - exact fit
from copy import deepcopy source = [1, 2, 3, 4] before = deepcopy(source) result = batches(source, 2) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[1, 2], [3, 4]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(type(row) is list for row in result), "Batches must be lists" assert len({id(row) for row in result}) == len(result), "Batches share storage" - oversize batch
from copy import deepcopy source = [-1, 0] before = deepcopy(source) result = batches(iter(source), 5) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[-1, 0]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(type(row) is list for row in result), "Batches must be lists" assert len({id(row) for row in result}) == len(result), "Batches share storage" - one-shot exhaustion
from copy import deepcopy source = [3, 1, 3] before = deepcopy(source) result = batches(iter(source), 2) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[3, 1], [3]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(type(row) is list for row in result), "Batches must be lists" assert len({id(row) for row in result}) == len(result), "Batches share storage" cursor = iter(source) assert batches(cursor, 2) == [[3, 1], [3]] assert list(cursor) == [], 'Input iterator was not consumed once' result[0].append(9) assert source == before and result[1] == [3], 'Batch ownership leaked'
Does small batch size make this returning function bounded-memory?
No. It returns all n entries in O(n) output storage and O(n) work. A yielding variant can bound its own working batch, but consumers may still retain all yielded batches.
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 milestoneCommunicate trade-offs
Attribute lookup follows precedence rules. A property can win over an instance dictionary entry, while an ordinary method can be shadowed there.
Understand first
An explanation that says Python always checks the instance first cannot predict computed attributes correctly.
Words you will see
- Descriptor
- An object on a class that participates in attribute access.
- Data descriptor
- A descriptor with setting or deleting behaviour that takes precedence over instance storage.
- Shadowing
- A nearer value hiding another attribute with the same name.
Trace class behaviour before storage
The property provides data-descriptor behaviour even without a user-written setter. Its getter therefore wins over the manually inserted code entry in __dict__. The ordinary method is a non-data descriptor, so the instance's label string wins instead.
The sample deliberately edits __dict__ to expose precedence. Ordinary code should assign through the public API rather than bypassing an object's invariants. A property without a setter normally rejects direct assignment.
Test the contract, not one storage layout
Objects with slots may not even have an instance dictionary. A proxy must preserve normal lookup before applying fallback behaviour. __getattr__ runs after normal lookup fails; __getattribute__ participates in every ordinary lookup and can recurse if written carelessly.
The example establishes observable language behaviour, not a constant-time guarantee for arbitrary properties. A getter can perform expensive work or raise an error. Ask whether computed access is pure, cached or resource-owning before presenting it as an ordinary field.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
@propertyInstall a data descriptor for code.
record = Record()Create an instance with ordinary attribute storage.
record.__dict__["code"] = "stored"Insert a value that the property still overrides.
print(record.label)Read the instance string that shadows the non-data method descriptor.
For each answer, distinguish language guarantees from CPython implementation details and average-case complexity from worst-case behaviour. Explain what you would measure or test when the environment changes rather than asserting a universal performance rule.
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.
Remove the method shadow.
Try: Delete the line assigning record.__dict__['label'] and call record.label() in the last print.
The method returns 'method'.
Attempt ordinary property assignment.
Try: Add record.code = 'new' before printing.
The real run raises AttributeError because the property has no setter.
Before you move on
After deleting record.__dict__['label'], what does record.label() return?
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 'method'. With the shadow removed, lookup finds and binds the class's function to the instance.
Review after the mock
A generator-based context manager acquires before yield and releases in finally around yield. That structure preserves cleanup when the body raises.
Understand first
An error-path rehearsal tests the resource lifetime more strongly than a successful with block alone.
Words you will see
- Context manager
- An object defining entry and exit around a with block.
- Yield boundary
- Where a generator-based manager hands control to the block.
- Exception propagation
- Allowing an unhandled error to continue to the caller.
Trace both sides of yield
Entering managed appends open. yield lends the resource to the with body. The body records use and raises ValueError. That error is thrown back at yield, so finally appends close before the outer except records caught.
Putting close after yield without finally would skip it on this exceptional path. Catching the error inside the manager and not re-raising would suppress it, changing the caller's contract.
Define lending versus ownership
The block borrows a resource whose lifetime belongs to the manager. Do not retain it after exit unless the resource explicitly permits that. The event list is only an offline lifetime model; it does not open a file or prove platform resource handling.
If acquisition itself can fail, register cleanup only for successfully acquired resources. ExitStack helps manage several dynamic acquisitions. For this fixed model, each event append adds one entry and the lifetime has a bounded number of steps.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
events.append("open")Record successful acquisition before lending.
yield "resource"Hand control and the borrowed value to the block.
events.append("close")Release while unwinding the body error.
events.append("caught")Observe that the original error still reached the caller.
Write down one misconception, one missing edge case and one topic to revisit. Schedule a later independent attempt rather than reading the answer repeatedly. The course reading milestone records reflection, not an interviewer certification.
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.
Test success.
Try: Delete raise ValueError('failed') from the body.
The events are open, use, close, with no caught entry.
Demonstrate the missing finally bug.
Try: Remove try/finally around yield and put close directly after yield.
On the failing body path close is skipped, exposing the resource-lifetime bug.
Before you move on
If the body succeeds without raising, which event is absent and does close still occur?
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
caught is absent. close still occurs because finally runs when the generator resumes normally after the with body.
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.