Demonstrate Default Arguments Are Evaluated Once

Hard ⏱ 18 min 31% acceptance ★★★★★ 4.9
Write a function make_id_generator() that, when called, returns a function next_id(_cache=[]) where _cache is used purely to demonstrate that default argument objects are created exactly once at function-definition time and persist across calls. next_id should append len(_cache) to _cache (using the current length as the next id before appending) and return that id. Show correct usage: creating the generator with make_id_generator() and calling the returned next_id() repeatedly should yield 0, 1, 2, ... in sequence, since the mutable default is deliberately reused here as internal state (a case where relying on the mutable-default quirk is intentional and documented, unlike the earlier bug-fix problem).

Examples

Example 1
Input
next_id = make_id_generator()
next_id()
next_id()
next_id()
Output
0, 1, 2
Explanation

Each call appends the current length of the shared _cache list as the new id, then returns it.

Constraints

  • A fresh call to make_id_generator() must produce an independent counter starting again at 0 (because it defines a brand-new inner function with its own default list).
  • Do not use any module-level or global state — everything must live in the default argument / closure.

Topics

Functionsdefault argumentsscope

Companies

MicrosoftOracle

Hints

Hint 1

A mutable default argument (like _cache=[]) is created once when the def statement inside make_id_generator runs, and that same list object is reused on every call to that particular next_id.

Hint 2

Calling make_id_generator() again creates a brand-new next_id function with its own brand-new default list, so the counters do not interfere with each other.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.