Temporary Environment Variable Context Manager

2.1.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `TemporaryEnvironment` as both a context manager and a decorator to temporarily set and restore environment variables. It's useful for isolating tests or managing environment-specific configurations.

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

view raw JSON →