environments.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import annotations
  15. import os
  16. from typing import Generic, TypeVar
  17. T = TypeVar("T")
  18. class EnvironmentVariable(Generic[T]):
  19. name: str
  20. default: T
  21. def __init__(self, name: str, default: T):
  22. self.name = name
  23. self.default = default
  24. def get(self) -> T:
  25. raise NotImplementedError()
  26. def set(self, value: T) -> None:
  27. raise NotImplementedError()
  28. def delete(self) -> None:
  29. del os.environ[self.name]
  30. def __repr__(self) -> str:
  31. return f"Env({self.name}={self.get()!r})"
  32. class StringEnvironmentVariable(EnvironmentVariable[str]):
  33. def __init__(self, name: str, default: str):
  34. super().__init__(name, default)
  35. assert isinstance(default, str), "default must be a string"
  36. def get(self) -> str:
  37. return os.getenv(self.name, self.default)
  38. def set(self, value: str) -> None:
  39. assert isinstance(value, str), "value must be a string"
  40. os.environ[self.name] = value
  41. class BooleanEnvironmentVariable(EnvironmentVariable[bool]):
  42. BOOLEAN_IS_SET = ("y", "yes", "t", "true", "on", "1")
  43. def __init__(self, name: str, default: bool):
  44. super().__init__(name, default)
  45. assert isinstance(default, bool), "default must be a boolean"
  46. def get(self) -> bool:
  47. default = str(self.default).lower()
  48. env_str = os.getenv(self.name, default).lower()
  49. return env_str in BooleanEnvironmentVariable.BOOLEAN_IS_SET
  50. def set(self, value: bool) -> None:
  51. assert isinstance(value, bool), "value must be a boolean"
  52. os.environ[self.name] = str(value).lower()
  53. class IntegerEnvironmentVariable(EnvironmentVariable[int]):
  54. def __init__(self, name: str, default: int):
  55. super().__init__(name, default)
  56. assert isinstance(default, int) and not isinstance(
  57. default, bool
  58. ), "default must be an integer"
  59. def get(self) -> int:
  60. try:
  61. return int(os.getenv(self.name, str(self.default)))
  62. except ValueError:
  63. return self.default
  64. def set(self, value: int) -> None:
  65. assert isinstance(value, int) and not isinstance(
  66. value, bool
  67. ), "value must be an integer"
  68. os.environ[self.name] = str(value)
  69. class EnvironmentVariableGuard(Generic[T]):
  70. variable: EnvironmentVariable[T]
  71. original_value: T
  72. def __init__(self, variable: EnvironmentVariable[T], value: T):
  73. self.variable = variable
  74. self.original_value = variable.get()
  75. self.variable.set(value)
  76. def __enter__(self) -> EnvironmentVariableGuard:
  77. return self
  78. def __exit__(self, exc_type, exc_value, traceback) -> None:
  79. self.variable.set(self.original_value)