import os
from contextlib import contextmanager
from typing import Dict, Iterator


@contextmanager
def temporary_env(values: Dict[str, str]) -> Iterator[None]:
    if not values:
        yield
        return
    old = {k: os.getenv(k) for k in values}
    try:
        for key, value in values.items():
            if value is None or value == "":
                continue
            os.environ[key] = value
        yield
    finally:
        for key, value in old.items():
            if value is None:
                os.environ.pop(key, None)
            else:
                os.environ[key] = value
