0
# Utilities
1
2
Utility functions for dynamic object instantiation from configuration, path resolution, and reflection-based object access. These functions provide the foundation for Hydra's dependency injection and configuration-driven object creation.
3
4
## Capabilities
5
6
### Object Instantiation
7
8
Instantiates objects and calls functions dynamically based on configuration with `_target_` field.
9
10
```python { .api }
11
def instantiate(config: Any, *args: Any, **kwargs: Any) -> Any:
12
"""
13
Instantiate an object from configuration.
14
15
Parameters:
16
- config: Configuration with _target_ field specifying class/function to instantiate
17
- *args: Additional positional arguments passed to target
18
- **kwargs: Additional keyword arguments passed to target
19
Special kwargs:
20
- _partial_: If True, return functools.partial object instead of calling
21
- _convert_: ConvertMode for recursive instantiation behavior
22
- _recursive_: If True, recursively instantiate nested configs
23
- _args_: List of positional arguments (alternative to *args)
24
25
Returns:
26
Instantiated object or function result
27
28
Raises:
29
InstantiationException: If instantiation fails
30
"""
31
32
# Alias for instantiate (backward compatibility)
33
call = instantiate
34
```
35
36
### Class Retrieval
37
38
Retrieves class objects from dot-path strings with type validation.
39
40
```python { .api }
41
def get_class(path: str) -> type:
42
"""
43
Get class from dotpath string.
44
45
Parameters:
46
- path: Dotpath to class (e.g., "my_module.MyClass")
47
48
Returns:
49
type: The class object
50
51
Raises:
52
ValueError: If path does not point to a class
53
Exception: If path cannot be resolved
54
"""
55
```
56
57
### Method and Function Retrieval
58
59
Retrieves callable objects from dot-path strings with callability validation.
60
61
```python { .api }
62
def get_method(path: str) -> Callable[..., Any]:
63
"""
64
Get callable from dotpath string.
65
66
Parameters:
67
- path: Dotpath to callable (e.g., "my_module.my_function")
68
69
Returns:
70
Callable: The callable object
71
72
Raises:
73
ValueError: If path does not point to a callable
74
Exception: If path cannot be resolved
75
"""
76
77
# Alias for backward compatibility
78
get_static_method = get_method
79
```
80
81
### Generic Object Retrieval
82
83
Retrieves any object from dot-path strings without type validation.
84
85
```python { .api }
86
def get_object(path: str) -> Any:
87
"""
88
Get any object from dotpath string.
89
90
Parameters:
91
- path: Dotpath to object (e.g., "my_module.my_object")
92
93
Returns:
94
Any: The retrieved object
95
96
Raises:
97
Exception: If path cannot be resolved
98
"""
99
```
100
101
### Path Utilities
102
103
Functions for working with file paths in Hydra context.
104
105
```python { .api }
106
def get_original_cwd() -> str:
107
"""
108
Get the original working directory when Hydra was launched.
109
110
Returns:
111
str: Original working directory path
112
113
Raises:
114
ValueError: If called before HydraConfig is initialized
115
"""
116
117
def to_absolute_path(path: str) -> str:
118
"""
119
Convert path to absolute, relative to original working directory.
120
121
Parameters:
122
- path: Path to convert (relative or absolute)
123
124
Returns:
125
str: Absolute path
126
"""
127
```
128
129
### Conversion Mode Enum
130
131
Controls recursive instantiation behavior.
132
133
```python { .api }
134
class ConvertMode(Enum):
135
"""
136
ConvertMode for instantiate function.
137
138
NONE: Keep DictConfig/ListConfig objects as-is
139
PARTIAL: Convert to dict/list, preserve structured configs
140
OBJECT: Convert structured configs to dataclass/attr instances
141
ALL: Convert everything to primitive containers
142
"""
143
NONE = "none"
144
PARTIAL = "partial"
145
OBJECT = "object"
146
ALL = "all"
147
```
148
149
## Usage Examples
150
151
### Basic Instantiation
152
153
```python
154
from hydra.utils import instantiate
155
from omegaconf import DictConfig
156
157
# Simple function call
158
config = DictConfig({
159
"_target_": "builtins.print",
160
"value": "Hello World"
161
})
162
instantiate(config) # Calls print("Hello World")
163
164
# Class instantiation
165
config = DictConfig({
166
"_target_": "pathlib.Path",
167
"path": "/tmp/example"
168
})
169
path_obj = instantiate(config) # Creates Path("/tmp/example")
170
```
171
172
### Advanced Instantiation Options
173
174
```python
175
from hydra.utils import instantiate, ConvertMode
176
177
# Partial instantiation
178
config = DictConfig({
179
"_target_": "functools.partial",
180
"func": "builtins.print",
181
"sep": " | "
182
})
183
partial_func = instantiate(config, _partial_=True)
184
partial_func("Hello", "World") # Prints: Hello | World
185
186
# Recursive instantiation with conversion control
187
config = DictConfig({
188
"_target_": "my_module.DataProcessor",
189
"database": {
190
"_target_": "my_module.Database",
191
"host": "localhost",
192
"port": 5432
193
},
194
"cache": {
195
"_target_": "my_module.Cache",
196
"size": 1000
197
}
198
})
199
200
processor = instantiate(config, _convert_="partial", _recursive_=True)
201
```
202
203
### Object Retrieval Functions
204
205
```python
206
from hydra.utils import get_class, get_method, get_object
207
208
# Get class object
209
Path = get_class("pathlib.Path")
210
path = Path("/tmp")
211
212
# Get function/method
213
print_func = get_method("builtins.print")
214
print_func("Hello World")
215
216
# Get any object (constant, variable, etc.)
217
version = get_object("sys.version_info")
218
print(version.major)
219
220
# Error handling
221
try:
222
invalid = get_class("my_module.not_a_class")
223
except ValueError as e:
224
print(f"Not a class: {e}")
225
```
226
227
### Path Utilities
228
229
```python
230
from hydra import main
231
from hydra.utils import get_original_cwd, to_absolute_path
232
233
@main(version_base=None, config_path="conf", config_name="config")
234
def my_app(cfg):
235
# Get original directory (before Hydra changed cwd)
236
original = get_original_cwd()
237
print(f"Original CWD: {original}")
238
239
# Convert relative path to absolute (relative to original cwd)
240
abs_path = to_absolute_path("data/input.txt")
241
print(f"Absolute path: {abs_path}")
242
243
# Useful for file operations
244
with open(to_absolute_path(cfg.data_file)) as f:
245
data = f.read()
246
```
247
248
### Instantiation with Configuration Merging
249
250
```python
251
from hydra.utils import instantiate
252
from omegaconf import DictConfig, OmegaConf
253
254
# Base configuration
255
base_config = DictConfig({
256
"_target_": "sklearn.ensemble.RandomForestClassifier",
257
"n_estimators": 100,
258
"random_state": 42
259
})
260
261
# Runtime overrides
262
overrides = DictConfig({
263
"max_depth": 10,
264
"min_samples_split": 5
265
})
266
267
# Merge and instantiate
268
merged = OmegaConf.merge(base_config, overrides)
269
model = instantiate(merged)
270
```
271
272
### Error Handling
273
274
```python
275
from hydra.utils import instantiate, get_class
276
from hydra.errors import InstantiationException
277
278
# Instantiation error handling
279
try:
280
config = DictConfig({
281
"_target_": "nonexistent.module.Class",
282
"param": "value"
283
})
284
obj = instantiate(config)
285
except InstantiationException as e:
286
print(f"Instantiation failed: {e}")
287
288
# Class retrieval error handling
289
try:
290
cls = get_class("os.path.join") # Function, not class
291
except ValueError as e:
292
print(f"Not a class: {e}")
293
```
294
295
### Integration with Structured Configs
296
297
```python
298
from dataclasses import dataclass
299
from hydra.utils import instantiate
300
from omegaconf import DictConfig
301
302
@dataclass
303
class ModelConfig:
304
_target_: str
305
learning_rate: float
306
batch_size: int
307
308
config = ModelConfig(
309
_target_="torch.optim.Adam",
310
learning_rate=0.001,
311
batch_size=32
312
)
313
314
# Convert to DictConfig for instantiation
315
dict_config = OmegaConf.structured(config)
316
optimizer = instantiate(dict_config, params=model.parameters())
317
```
318
319
### Custom Instantiation Hooks
320
321
```python
322
from hydra.utils import instantiate
323
324
# Custom factory function
325
def create_database_connection(host, port, **kwargs):
326
# Custom connection logic
327
return DatabaseConnection(host, port, **kwargs)
328
329
config = DictConfig({
330
"_target_": "__main__.create_database_connection",
331
"host": "localhost",
332
"port": 5432,
333
"pool_size": 10
334
})
335
336
db = instantiate(config)
337
```