Last active
December 12, 2023 16:43
-
-
Save igniteflow/7267431 to your computer and use it in GitHub Desktop.
A Python context manager for setting/unsetting environment variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
""" | |
Usage: | |
with env_var('MY_VAR', 'foo'): | |
# is set here | |
# does not exist here | |
""" | |
@contextmanager | |
def env_var(key, value): | |
os.environ[key] = value | |
yield | |
del os.environ[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This further improves over @jdemaeyer's snippet. It allows using the context manager to temporarily unset an env variable (e.g.
with environ(HOME=None)
).Also, because it uses
pop()
, it will not choke if an environment variable that was added by the context manager has been deleted by the wrapped code.