A framework for elegantly configuring complex applications
—
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.
Instantiates objects and calls functions dynamically based on configuration with _target_ field.
def instantiate(config: Any, *args: Any, **kwargs: Any) -> Any:
"""
Instantiate an object from configuration.
Parameters:
- config: Configuration with _target_ field specifying class/function to instantiate
- *args: Additional positional arguments passed to target
- **kwargs: Additional keyword arguments passed to target
Special kwargs:
- _partial_: If True, return functools.partial object instead of calling
- _convert_: ConvertMode for recursive instantiation behavior
- _recursive_: If True, recursively instantiate nested configs
- _args_: List of positional arguments (alternative to *args)
Returns:
Instantiated object or function result
Raises:
InstantiationException: If instantiation fails
"""
# Alias for instantiate (backward compatibility)
call = instantiateRetrieves class objects from dot-path strings with type validation.
def get_class(path: str) -> type:
"""
Get class from dotpath string.
Parameters:
- path: Dotpath to class (e.g., "my_module.MyClass")
Returns:
type: The class object
Raises:
ValueError: If path does not point to a class
Exception: If path cannot be resolved
"""Retrieves callable objects from dot-path strings with callability validation.
def get_method(path: str) -> Callable[..., Any]:
"""
Get callable from dotpath string.
Parameters:
- path: Dotpath to callable (e.g., "my_module.my_function")
Returns:
Callable: The callable object
Raises:
ValueError: If path does not point to a callable
Exception: If path cannot be resolved
"""
# Alias for backward compatibility
get_static_method = get_methodRetrieves any object from dot-path strings without type validation.
def get_object(path: str) -> Any:
"""
Get any object from dotpath string.
Parameters:
- path: Dotpath to object (e.g., "my_module.my_object")
Returns:
Any: The retrieved object
Raises:
Exception: If path cannot be resolved
"""Functions for working with file paths in Hydra context.
def get_original_cwd() -> str:
"""
Get the original working directory when Hydra was launched.
Returns:
str: Original working directory path
Raises:
ValueError: If called before HydraConfig is initialized
"""
def to_absolute_path(path: str) -> str:
"""
Convert path to absolute, relative to original working directory.
Parameters:
- path: Path to convert (relative or absolute)
Returns:
str: Absolute path
"""Controls recursive instantiation behavior.
class ConvertMode(Enum):
"""
ConvertMode for instantiate function.
NONE: Keep DictConfig/ListConfig objects as-is
PARTIAL: Convert to dict/list, preserve structured configs
OBJECT: Convert structured configs to dataclass/attr instances
ALL: Convert everything to primitive containers
"""
NONE = "none"
PARTIAL = "partial"
OBJECT = "object"
ALL = "all"from hydra.utils import instantiate
from omegaconf import DictConfig
# Simple function call
config = DictConfig({
"_target_": "builtins.print",
"value": "Hello World"
})
instantiate(config) # Calls print("Hello World")
# Class instantiation
config = DictConfig({
"_target_": "pathlib.Path",
"path": "/tmp/example"
})
path_obj = instantiate(config) # Creates Path("/tmp/example")from hydra.utils import instantiate, ConvertMode
# Partial instantiation
config = DictConfig({
"_target_": "functools.partial",
"func": "builtins.print",
"sep": " | "
})
partial_func = instantiate(config, _partial_=True)
partial_func("Hello", "World") # Prints: Hello | World
# Recursive instantiation with conversion control
config = DictConfig({
"_target_": "my_module.DataProcessor",
"database": {
"_target_": "my_module.Database",
"host": "localhost",
"port": 5432
},
"cache": {
"_target_": "my_module.Cache",
"size": 1000
}
})
processor = instantiate(config, _convert_="partial", _recursive_=True)from hydra.utils import get_class, get_method, get_object
# Get class object
Path = get_class("pathlib.Path")
path = Path("/tmp")
# Get function/method
print_func = get_method("builtins.print")
print_func("Hello World")
# Get any object (constant, variable, etc.)
version = get_object("sys.version_info")
print(version.major)
# Error handling
try:
invalid = get_class("my_module.not_a_class")
except ValueError as e:
print(f"Not a class: {e}")from hydra import main
from hydra.utils import get_original_cwd, to_absolute_path
@main(version_base=None, config_path="conf", config_name="config")
def my_app(cfg):
# Get original directory (before Hydra changed cwd)
original = get_original_cwd()
print(f"Original CWD: {original}")
# Convert relative path to absolute (relative to original cwd)
abs_path = to_absolute_path("data/input.txt")
print(f"Absolute path: {abs_path}")
# Useful for file operations
with open(to_absolute_path(cfg.data_file)) as f:
data = f.read()from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf
# Base configuration
base_config = DictConfig({
"_target_": "sklearn.ensemble.RandomForestClassifier",
"n_estimators": 100,
"random_state": 42
})
# Runtime overrides
overrides = DictConfig({
"max_depth": 10,
"min_samples_split": 5
})
# Merge and instantiate
merged = OmegaConf.merge(base_config, overrides)
model = instantiate(merged)from hydra.utils import instantiate, get_class
from hydra.errors import InstantiationException
# Instantiation error handling
try:
config = DictConfig({
"_target_": "nonexistent.module.Class",
"param": "value"
})
obj = instantiate(config)
except InstantiationException as e:
print(f"Instantiation failed: {e}")
# Class retrieval error handling
try:
cls = get_class("os.path.join") # Function, not class
except ValueError as e:
print(f"Not a class: {e}")from dataclasses import dataclass
from hydra.utils import instantiate
from omegaconf import DictConfig
@dataclass
class ModelConfig:
_target_: str
learning_rate: float
batch_size: int
config = ModelConfig(
_target_="torch.optim.Adam",
learning_rate=0.001,
batch_size=32
)
# Convert to DictConfig for instantiation
dict_config = OmegaConf.structured(config)
optimizer = instantiate(dict_config, params=model.parameters())from hydra.utils import instantiate
# Custom factory function
def create_database_connection(host, port, **kwargs):
# Custom connection logic
return DatabaseConnection(host, port, **kwargs)
config = DictConfig({
"_target_": "__main__.create_database_connection",
"host": "localhost",
"port": 5432,
"pool_size": 10
})
db = instantiate(config)Install with Tessl CLI
npx tessl i tessl/pypi-hydra-core