medium +20 pts

Context Variable Scope

Implement a context manager that safely modifies a global variable only within its block.

You are given a module that uses a global variable `current_user`. You must implement a context manager class `user_context` that temporarily sets `current_user` to a specified value when entering a `with` block and restores the original value when exiting the block. The restoration must happen even if an exception is raised inside the `with` block. The class must be defined with the exact signature: ```python class user_context: def __init__(self, new_user): ... def __enter__(self): ... def __exit__(self, exc_type, exc_val, exc_tb): ... ``` Behavior: - On entering, set the global variable `current_user` to `new_user`. - On exiting, restore `current_user` to its previous value. - If an exception occurs inside the `with` block, the exception must still propagate after the restoration (i.e., do not suppress it). - The context manager must work even if the global variable didn't exist before the block; in that case, after the block the global variable should be removed (as if it never existed). Assume the global variable is named exactly `current_user` and is defined in the same module where the class is defined. The class should be placed in that module, and the grading code will manipulate `current_user` outside the context manager in a way that is consistent with the behavior described.

Constraints

- The `new_user` argument can be any value (e.g., string, int, None). - The context manager does not need to be re-entrant. - The restoration must be exact: the variable's previous binding is restored, including if it was not defined.

Example

>>> current_user = 'alice'
>>> with user_context('bob'):
...     print(current_user)
bob
>>> print(current_user)
alice

>>> if 'current_user' in globals(): del current_user
>>> with user_context('carol'):
...     print(current_user)
carol
>>> 'current_user' in globals()
False
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use `globals()` to access and modify the global variable `current_user`.
In `__enter__`, save whether the global existed, and if so, its old value.
In `__exit__`, restore the old value or delete the global if it didn't exist.
Return `False` (or `None`) from `__exit__` so exceptions propagate.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.