import logging
logging.basicConfig(level=logging.WARNING) # Configure logging
class Config:
"""
A class to manage configuration values with defensive checks.
"""
def __init__(self):
self._config = {} # Internal dictionary to store config values
def set(self, key, value):
"""
Sets a configuration value with defensive checks.
"""
if not isinstance(key, str):
raise TypeError("Key must be a string.")
if key in self._config:
existing_value = self._config[key]
if not isinstance(existing_value, type(value)):
raise TypeError(f"Value for key '{key}' must be of type {type(existing_value)}, but got {type(value)}")
try:
self._config[key] = value
except Exception as e:
logging.error(f"Error setting config value for '{key}': {e}")
raise
def get(self, key, default=None):
"""
Retrieves a configuration value with a default if not found.
"""
if key not in self._config:
return default
return self._config[key]
def check(self, key, min_value=None, max_value=None):
"""
Checks if a configuration value is within specified limits.
"""
value = self.get(key)
if value is not None:
if min_value is not None and value < min_value:
raise ValueError(f"Value for '{key}' must be at least {min_value}.")
if max_value is not None and value > max_value:
raise ValueError(f"Value for '{key}' must be no more than {max_value}.")
def print_config(self):
"""Prints the current configuration."""
print(self._config)
Add your comment