env_var.py 1011 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. from __future__ import annotations
  2. from contextlib import suppress
  3. from typing import TYPE_CHECKING
  4. from .convert import convert
  5. if TYPE_CHECKING:
  6. from collections.abc import Mapping
  7. from typing import Any
  8. from .convert import TypeData
  9. def get_env_var(key: str, as_type: TypeData, env: Mapping[str, str]) -> tuple[Any, str] | None:
  10. """Get the environment variable option.
  11. :param key: the config key requested
  12. :param as_type: the type we would like to convert it to
  13. :param env: environment variables to use
  14. :returns: the converted value and source, or None if not set
  15. """
  16. environ_key = f"VIRTUALENV_{key.upper()}"
  17. if env.get(environ_key):
  18. value = env[environ_key]
  19. with suppress(Exception): # note the converter already logs a warning when failures happen
  20. source = f"env var {environ_key}"
  21. as_type = convert(value, as_type, source)
  22. return as_type, source
  23. return None
  24. __all__ = [
  25. "get_env_var",
  26. ]