runtime
328 / 500
question 328 Decorators & Context Managers · medium

Temporary environment variables

Tests of a command-line tool need to run it with particular environment variables (see CLI & Automation) and must leave the environment exactly as they found it. Write env_vars(**changes) with @contextmanager: for the block, set each variable to its value, or remove it when the value is None; afterwards restore every variable to its old value, or remove it if it didn't exist before, even when the block raises.

Context managerenv_vars(**changes), e.g. with env_vars(REPORT_CURRENCY="EUR", DEBUG=None):
Duringos.environ has the new values; a None value means the variable is absent
Afteros.environ is exactly as before for every name in changes; exceptions propagate

Loading your progress…

Temporary environment variables — Python practice · Runtime