0
# Initialization
1
2
Context managers for programmatic Hydra initialization in different scenarios. These enable using Hydra's configuration composition capabilities outside of the main application decorator pattern.
3
4
## Capabilities
5
6
### File-Based Initialization
7
8
Initializes Hydra with configuration files from a directory path relative to the calling module.
9
10
```python { .api }
11
class initialize:
12
def __init__(
13
self,
14
config_path: Optional[str] = None,
15
job_name: Optional[str] = None,
16
caller_stack_depth: int = 1,
17
version_base: Optional[str] = None
18
) -> None:
19
"""
20
Initialize Hydra with config path relative to caller.
21
22
Parameters:
23
- config_path: Path relative to the parent of the caller.
24
Can use "pkg://" prefix for package resources.
25
If None, no directory is added to config search path.
26
- job_name: Value for hydra.job.name (auto-detected if None)
27
- caller_stack_depth: Stack depth of caller (default 1 for direct caller)
28
- version_base: Hydra version compatibility base
29
"""
30
```
31
32
### Module-Based Initialization
33
34
Initializes Hydra with configurations from an importable Python module.
35
36
```python { .api }
37
class initialize_config_module:
38
def __init__(
39
self,
40
config_module: str,
41
job_name: str = "app",
42
version_base: Optional[str] = None
43
) -> None:
44
"""
45
Initialize Hydra with config module.
46
47
Parameters:
48
- config_module: Absolute module name (e.g., "foo.bar.conf")
49
Module must be importable with __init__.py
50
- job_name: Value for hydra.job.name (default "app")
51
- version_base: Hydra version compatibility base
52
"""
53
```
54
55
### Directory-Based Initialization
56
57
Initializes Hydra with configurations from an absolute directory path.
58
59
```python { .api }
60
class initialize_config_dir:
61
def __init__(
62
self,
63
config_dir: str,
64
job_name: str = "app",
65
version_base: Optional[str] = None
66
) -> None:
67
"""
68
Initialize Hydra with absolute config directory.
69
70
Parameters:
71
- config_dir: Absolute filesystem path to config directory
72
- job_name: Value for hydra.job.name (default "app")
73
- version_base: Hydra version compatibility base
74
75
Raises:
76
HydraException: If config_dir is not an absolute path
77
"""
78
```
79
80
## Usage Examples
81
82
### Basic File-Based Initialization
83
84
```python
85
from hydra import initialize, compose
86
87
# Initialize with relative path
88
with initialize(version_base=None, config_path="conf"):
89
cfg = compose(config_name="config")
90
print(cfg.db.driver)
91
92
# Initialize with package path
93
with initialize(version_base=None, config_path="pkg://my_package.conf"):
94
cfg = compose(config_name="config")
95
print(cfg)
96
97
# Initialize with no config path (structured configs only)
98
with initialize(version_base=None, config_path=None):
99
cfg = compose(config_name="config") # Must exist in ConfigStore
100
```
101
102
### Module-Based Initialization
103
104
```python
105
from hydra import initialize_config_module, compose
106
107
# Initialize with Python module
108
with initialize_config_module(version_base=None, config_module="my_app.conf"):
109
cfg = compose(config_name="config")
110
111
# Custom job name
112
with initialize_config_module(
113
version_base=None,
114
config_module="my_app.conf",
115
job_name="custom_job"
116
):
117
cfg = compose(config_name="config")
118
print(cfg.hydra.job.name) # Will be "custom_job"
119
```
120
121
### Directory-Based Initialization
122
123
```python
124
from hydra import initialize_config_dir, compose
125
import os
126
127
# Must use absolute path
128
config_dir = os.path.abspath("./conf")
129
with initialize_config_dir(version_base=None, config_dir=config_dir):
130
cfg = compose(config_name="config")
131
132
# Error: relative path not allowed
133
try:
134
with initialize_config_dir(version_base=None, config_dir="./conf"):
135
pass
136
except HydraException as e:
137
print("Relative paths not allowed")
138
```
139
140
### Nested Context Management
141
142
Initialization contexts can be nested and properly restore state:
143
144
```python
145
from hydra import initialize, compose
146
147
# Outer context
148
with initialize(version_base=None, config_path="conf1"):
149
cfg1 = compose(config_name="config")
150
151
# Inner context temporarily overrides
152
with initialize(version_base=None, config_path="conf2"):
153
cfg2 = compose(config_name="config")
154
155
# Back to outer context
156
cfg1_again = compose(config_name="config")
157
```
158
159
### Integration with ConfigStore
160
161
All initialization methods work with structured configs:
162
163
```python
164
from dataclasses import dataclass
165
from hydra import initialize, compose
166
from hydra.core.config_store import ConfigStore
167
168
@dataclass
169
class Config:
170
name: str = "default"
171
value: int = 42
172
173
# Register structured config
174
cs = ConfigStore.instance()
175
cs.store(name="my_config", node=Config)
176
177
# Can use any initialization method
178
with initialize(version_base=None, config_path=None):
179
cfg = compose(config_name="my_config")
180
print(f"{cfg.name}: {cfg.value}")
181
```
182
183
### Error Handling
184
185
Common initialization errors:
186
187
```python
188
from hydra import initialize_config_dir, HydraException
189
190
# Relative path error
191
try:
192
with initialize_config_dir(version_base=None, config_dir="relative/path"):
193
pass
194
except HydraException as e:
195
print("Must use absolute path")
196
197
# Module import error
198
try:
199
with initialize_config_module(version_base=None, config_module="nonexistent.module"):
200
pass
201
except (ImportError, ModuleNotFoundError) as e:
202
print("Module not found or not importable")
203
```
204
205
### Context Manager Protocol
206
207
All initialization classes implement the context manager protocol:
208
209
```python
210
# Can be used with explicit enter/exit
211
init_ctx = initialize(version_base=None, config_path="conf")
212
init_ctx.__enter__()
213
try:
214
cfg = compose(config_name="config")
215
finally:
216
init_ctx.__exit__(None, None, None)
217
218
# But with statement is recommended
219
with initialize(version_base=None, config_path="conf"):
220
cfg = compose(config_name="config")
221
```
222
223
### Caller Stack Depth
224
225
The `caller_stack_depth` parameter controls path resolution:
226
227
```python
228
def my_init_wrapper():
229
# Need stack depth 2 to find config relative to calling function
230
with initialize(
231
version_base=None,
232
config_path="conf",
233
caller_stack_depth=2
234
):
235
return compose(config_name="config")
236
237
def caller():
238
# Config path resolved relative to this function
239
return my_init_wrapper()
240
```
241
242
### Version Base Compatibility
243
244
Control backward compatibility behavior:
245
246
```python
247
# Use current version behavior (recommended)
248
with initialize(version_base=None, config_path="conf"):
249
cfg = compose(config_name="config")
250
251
# Use Hydra 1.1 compatible behavior
252
with initialize(version_base="1.1", config_path="conf"):
253
cfg = compose(config_name="config")
254
```