Temporary Environment Variable Context Manager
tempenv is a lightweight Python context manager and decorator for temporarily setting and unsetting environment variables. It guarantees that environment variables are restored to their original state after the context exits or a decorated function completes, making it ideal for testing or local development. The current version is 2.1.0, with releases primarily driven by Python version compatibility updates and minor maintenance.
Common errors
-
TypeError: TemporaryEnvironment.__init__() missing 1 required positional argument: 'value'
cause Attempting to initialize `TemporaryEnvironment()` without any arguments on `tempenv` versions prior to 2.0.0. The constructor historically required at least one environment variable to be set.fixProvide at least one `key=value` pair, e.g., `with TemporaryEnvironment(FOO='bar'):`, or upgrade to `tempenv>=2.0.0` which allows empty initialization using `with TemporaryEnvironment():`. -
TypeError: TemporaryEnvironment.__init__() takes 1 positional argument but 2 were given
cause Trying to pass a dictionary of environment variables directly as a positional argument (e.g., `TemporaryEnvironment({'MY_VAR': 'value'})`) instead of using keyword arguments or unpacking the dictionary.fixUnpack the dictionary using the `**` operator: `with TemporaryEnvironment(**{'MY_VAR': 'value'}):` or pass variables as individual keyword arguments: `with TemporaryEnvironment(MY_VAR='value'):`.
Warnings
- breaking Dropped support for older Python versions. `tempenv>=2.0.0` requires Python 3.7+ (dropped 3.6). `tempenv>=2.1.0` further dropped Python 3.7 and 3.8, now requiring Python 3.9+.
- breaking The internal implementation of `TemporaryEnvironment` changed to use `ContextDecorator` in v2.0.0. While the public API remains largely compatible, subtle behavioral differences might arise in highly complex or deeply nested scenarios if previous reliance was on specific pre-2.0.0 internals.
- gotcha Prior to v2.0.0, the `TemporaryEnvironment` initializer required at least one `key=value` pair. Attempting to initialize it without any arguments (e.g., `TemporaryEnvironment()`) would raise a `TypeError`.
Install
-
pip install tempenv
Imports
- TemporaryEnvironment
from tempenv import TemporaryEnvironment
Quickstart
import os
from tempenv import TemporaryEnvironment
# --- Usage as a Context Manager ---
# Get current value for example
original_path = os.environ.get('PATH')
print(f"Initial PATH (might be long, truncated): {original_path[:50]}...")
with TemporaryEnvironment(PATH='/tmp/test_path'):
# Inside this block, PATH is temporarily changed
current_path = os.environ.get('PATH')
print(f"Inside context: PATH={current_path}")
assert current_path == '/tmp/test_path'
# Outside the block, PATH is restored to its original value
restored_path = os.environ.get('PATH')
print(f"After context: PATH (truncated): {restored_path[:50]}...")
assert restored_path == original_path
# --- Usage as a Decorator ---
@TemporaryEnvironment(MY_API_KEY='temp_key_123')
def fetch_data_with_temp_key():
print(f"\nInside decorated function: MY_API_KEY={os.environ.get('MY_API_KEY')}")
assert os.environ.get('MY_API_KEY') == 'temp_key_123'
print(f"Before decorated call: MY_API_KEY={os.environ.get('MY_API_KEY')}")
fetch_data_with_temp_key()
print(f"After decorated call: MY_API_KEY={os.environ.get('MY_API_KEY')}")
# MY_API_KEY is unset or restored after the function returns
assert os.environ.get('MY_API_KEY') is None