1. import logging
  2. logging.basicConfig(level=logging.WARNING) # Configure logging
  3. class Config:
  4. """
  5. A class to manage configuration values with defensive checks.
  6. """
  7. def __init__(self):
  8. self._config = {} # Internal dictionary to store config values
  9. def set(self, key, value):
  10. """
  11. Sets a configuration value with defensive checks.
  12. """
  13. if not isinstance(key, str):
  14. raise TypeError("Key must be a string.")
  15. if key in self._config:
  16. existing_value = self._config[key]
  17. if not isinstance(existing_value, type(value)):
  18. raise TypeError(f"Value for key '{key}' must be of type {type(existing_value)}, but got {type(value)}")
  19. try:
  20. self._config[key] = value
  21. except Exception as e:
  22. logging.error(f"Error setting config value for '{key}': {e}")
  23. raise
  24. def get(self, key, default=None):
  25. """
  26. Retrieves a configuration value with a default if not found.
  27. """
  28. if key not in self._config:
  29. return default
  30. return self._config[key]
  31. def check(self, key, min_value=None, max_value=None):
  32. """
  33. Checks if a configuration value is within specified limits.
  34. """
  35. value = self.get(key)
  36. if value is not None:
  37. if min_value is not None and value < min_value:
  38. raise ValueError(f"Value for '{key}' must be at least {min_value}.")
  39. if max_value is not None and value > max_value:
  40. raise ValueError(f"Value for '{key}' must be no more than {max_value}.")
  41. def print_config(self):
  42. """Prints the current configuration."""
  43. print(self._config)

Add your comment