feat(environment): add EnvVar.override to set a variable for a with block and restore it afterwards

BE
2d ago
+159-3

Type of change

  • New feature (non-breaking change which adds functionality)

Description

EnvVar.override(value) sets an environment variable to a typed value for a with block and afterwards restores its previous raw value, or unsets it again, also when the block raises. The value is written the way EnvVar.set writes it (None unsets), and the set callbacks run on entry and on exit.

Tests here and in apps that declare their own EnvVars currently go through the variable's name and a string in the format the getter parses, or pair EnvVar.set with a hand-written restore:

# before
monkeypatch.setenv(environment.REFLEX_SOCKET_TIMEOUT.name, "5s")

# after
with environment.REFLEX_SOCKET_TIMEOUT.override(timedelta(seconds=5)):
    ...

Writing os.environ directly also skips the callbacks registered with _on_env_var_set, which is why the restore_env_mode fixture in tests/units/reflex_base/vars/test_base.py clears _type_check_depth's cache itself; override restores through the same path as set. It does not depend on pytest, so it works in fixtures (with ...: yield) and outside tests alike.

Tests and lint

  • uv run pytest tests/units/test_environment.py: 118 passed (new: restore of a set and of an unset variable, None, typed round trip for duration/enum/path list, nested blocks unwinding on an exception with callbacks)
  • pre-commit hooks on the changed files (ruff, codespell, pyright, ty)