-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
217 lines (168 loc) · 6.66 KB
/
config.py
File metadata and controls
217 lines (168 loc) · 6.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""
Configuration Expert - Singleton configuration manager
Handles loading and caching of YAML configuration files.
Provides easy access to configuration values throughout the application.
"""
import yaml
from pathlib import Path
from typing import Any, Optional, Dict
class ConfigExpert:
"""
Singleton configuration manager
Loads YAML configuration once and provides easy access via get() method.
Usage:
# Initialize with config file
config = ConfigExpert.get_instance("experiments/example.yaml")
# Access values anywhere in code
test_mode = ConfigExpert.get_instance().get("test_mode")
models = ConfigExpert.get_instance().get("models")
# Nested values with dot notation
name = ConfigExpert.get_instance().get("experiment.name")
# With default values
timeout = ConfigExpert.get_instance().get("timeout", default=30)
"""
_instance = None
_config = None
_config_path = None
def __new__(cls, config_path: Optional[str] = None):
"""Singleton pattern: only one instance allowed"""
if cls._instance is None:
cls._instance = super(ConfigExpert, cls).__new__(cls)
return cls._instance
def __init__(self, config_path: Optional[str] = None):
"""
Initialize configuration (only once)
Args:
config_path: Path to YAML configuration file
"""
# If config already loaded and no new path provided, skip
if self._config is not None and config_path is None:
return
# Load new config if path provided
if config_path is not None:
self._load_config(config_path)
def _load_config(self, config_path: str):
"""
Load configuration from YAML file
Args:
config_path: Path to YAML file
"""
config_path = str(Path(config_path).resolve())
# Skip if already loaded from this path
if self._config_path == config_path and self._config is not None:
print(f"✅️ Config already loaded from: {config_path}")
return
print(f"📖 Loading configuration from: {config_path}")
try:
with open(config_path, 'r', encoding='utf-8') as f:
self._config = yaml.safe_load(f)
self._config_path = config_path
print(f"✅️ Configuration loaded successfully")
except FileNotFoundError:
raise FileNotFoundError(f"Configuration file not found: {config_path}")
except yaml.YAMLError as e:
raise ValueError(f"Invalid YAML in configuration file: {e}")
except Exception as e:
raise Exception(f"Error loading configuration: {e}")
@classmethod
def get_instance(cls, config_path: Optional[str] = None) -> 'ConfigExpert':
"""
Get singleton instance
Args:
config_path: Optional path to config file (only needed on first call)
Returns:
ConfigExpert instance
"""
if cls._instance is None:
if config_path is None:
raise ValueError(
"ConfigExpert must be initialized with config_path on first call. "
"Usage: ConfigExpert.get_instance('path/to/config.yaml')"
)
cls._instance = cls(config_path)
elif config_path is not None:
# Update config if new path provided
cls._instance._load_config(config_path)
return cls._instance
def get(self, key: str, default: Any = None) -> Any:
"""
Get configuration value by key
Supports dot notation for nested values.
Args:
key: Configuration key (supports dot notation, e.g., "experiment.name")
default: Default value if key not found
Returns:
Configuration value or default
Examples:
config.get("models")
config.get("experiment.name")
config.get("timeout", default=30)
"""
if self._config is None:
raise RuntimeError(
"Configuration not loaded. "
"Initialize with: ConfigExpert.get_instance('path/to/config.yaml')"
)
# Handle dot notation for nested keys
if '.' in key:
keys = key.split('.')
value = self._config
for k in keys:
if isinstance(value, dict) and k in value:
value = value[k]
else:
return default
return value
# Simple key lookup
return self._config.get(key, default)
def get_all(self) -> Dict:
"""
Get entire configuration dictionary
Returns:
Complete configuration as dictionary
"""
if self._config is None:
raise RuntimeError("Configuration not loaded")
return self._config.copy()
def has(self, key: str) -> bool:
"""
Check if configuration key exists
Args:
key: Configuration key (supports dot notation)
Returns:
True if key exists, False otherwise
"""
if self._config is None:
return False
# Handle dot notation
if '.' in key:
keys = key.split('.')
value = self._config
for k in keys:
if isinstance(value, dict) and k in value:
value = value[k]
else:
return False
return True
return key in self._config
def reload(self, config_path: Optional[str] = None):
"""
Reload configuration from file
Args:
config_path: Optional new config path, or reload from current path
"""
path = config_path or self._config_path
if path is None:
raise ValueError("No config path available for reload")
# Force reload by clearing config first
self._config = None
self._load_config(path)
def get_config_path(self) -> Optional[str]:
"""Get path of currently loaded configuration file"""
return self._config_path
@classmethod
def reset(cls):
"""Reset singleton (useful for testing)"""
cls._instance = None
cls._config = None
cls._config_path = None