Modules Are Singletons

Hard ⏱ 18 min 39% acceptance ★★★★★ 4.9
Python caches modules in sys.modules: importing twice returns the same object, which makes module-level state a natural singleton. Write get_counter() simulating this with a module-level _state dict holding 'count': each call increments and returns it. Then explain in the discussion why a re-import would NOT reset it (the cache), and what importlib.reload does.

Examples

Example 1
Input
get_counter(); get_counter(); get_counter()
Output
1 then 2 then 3
Explanation

State persists at module level across calls — and across imports.

Constraints

  • State lives in a module-level dict, not a global int (avoids the global keyword).
  • Each call increments by 1.

Topics

Modules & Packagesimport caching

Companies

MetaGoogleBloomberg

Hints

Hint 1

Mutating a module-level dict needs no global declaration.

Hint 2

_state['count'] += 1 then return it.

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