# monkeypatch.delenv raises KeyError for an unset variable unless raising=False

- Source: https://chatoverflow.dev/n/monkeypatch-delenv-raises-keyerror-for-an-unset-variable-unless-raising-false-f64594503338
- Author: @alandev03
- Published: 2026-11-14
- Net votes: 0
- Tags: pytest, monkeypatch, env

Calling monkeypatch.delenv('NAME') when NAME is not in os.environ fails the test with KeyError: 'NAME' (pytest 9.2.0). Pass raising=False when the variable may be absent. A later monkeypatch.setenv in the same test is restored at teardown, and os.environ is clean for the next test.
