1. import os
  2. import logging
  3. class EnvVarWrapper:
  4. """
  5. Wraps environment variable access for testing purposes,
  6. providing a consistent interface and support for older Python versions.
  7. """
  8. def __init__(self, var_name, default_value=None):
  9. """
  10. Initializes the wrapper for a specific environment variable.
  11. Args:
  12. var_name (str): The name of the environment variable.
  13. default_value (any, optional): The default value to use if the environment variable is not set. Defaults to None.
  14. """
  15. self.var_name = var_name
  16. self.default_value = default_value
  17. self.value = os.environ.get(var_name, self.default_value) # Get env var, use default if missing
  18. self.is_set = bool(self.value) #track if variable is set
  19. def get(self):
  20. """
  21. Returns the value of the environment variable.
  22. Returns:
  23. any: The value of the environment variable.
  24. """
  25. return self.value
  26. def is_enabled(self):
  27. """
  28. Returns True if the environment variable is set and not empty, False otherwise.
  29. """
  30. return self.is_set
  31. def set_default(self, new_default):
  32. """
  33. Updates the default value of the environment variable.
  34. """
  35. self.default_value = new_default
  36. self.value = os.environ.get(self.var_name, self.default_value)
  37. self.is_set = bool(self.value)
  38. if __name__ == '__main__':
  39. # Example Usage
  40. logging.basicConfig(level=logging.INFO)
  41. # Create a wrapper for a variable
  42. db_host = EnvVarWrapper("DB_HOST", "localhost")
  43. db_port = EnvVarWrapper("DB_PORT", "5432")
  44. debug_mode = EnvVarWrapper("DEBUG", False)
  45. # Get the values
  46. host = db_host.get()
  47. port = db_port.get()
  48. debug = debug_mode.get()
  49. print(f"DB Host: {host}")
  50. print(f"DB Port: {port}")
  51. print(f"Debug Mode: {debug}")
  52. #Check if variable is set
  53. print(f"DB Host is enabled: {db_host.is_enabled()}")
  54. print(f"Debug Mode is enabled: {debug_mode.is_enabled()}")
  55. #Set new default value
  56. db_port.set_default(5433)
  57. print(f"DB Port after setting new default: {db_port.get()}")

Add your comment