Environment Variable Context Manager
Low maintenance activity. Last release 20 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install tempenvtempenv
Manage environment variables in a temporary scope.
Some products use environment variables as a primary means to supply credentials. To ensure the lifetime of exposed credentials is short, wrap them in a TemporaryEnvironment so that they are automatically destroyed on scope exit.
You can:
- Set or unset environment variables inside a
withcode block, - Get a warning if the code block modifies one of the environment variables,
- Optionally bypass restoration of the original environment variable value if the code block modifies the environment variable.
Install
Install the latest version of tempenv:
pip install tempenv
Examples
Each of these examples can be found in the tests.
Set some environment variables temporarily: (see tests/example_set_test.py):
def test_set(self):
user_before = os.environ.get("USER")
with TemporaryEnvironment({"USER": "nobody", "OTHER": "foo"}):
assert os.environ.get("USER") == "nobody"
assert os.environ.get("OTHER") == "foo"
assert os.environ.get("USER") == user_before
Changing the value to None will unset the environment variable during
the code block
(see tests/example_unset_test.py):
def test_unset(self):
os.environ["DEBUG"] = "1"
with TemporaryEnvironment({"DEBUG": None}):
assert "DEBUG" not in os.environ
assert "DEBUG" in os.environ
Changing a temporary environment variable during the scope will cause a warning (see tests/example_overwrite_test.py):
def test_overwritten_in_context(self):
with self.assertWarnsRegex(EnvironmentVariableChangedWarning, "FOO"):
with TemporaryEnvironment({"FOO": "BAR"}):
os.environ["FOO"] = "SAM"