One of the best ways to drive different behavior in an application is to instantiate different implementations of an interface. The code using the instantiated object only knows the interface which remains constant, but the behavior is determined by the actual object instance.
hydra.utils.instantiate() (and its alias
hydra.utils.call()) for instantiating objects and calling functions. Prefer
instantiate for creating objects and
call for invoking functions.
- Constructing an object by calling the
- Calling functions, static functions, class methods and other callable global objects
Instantiate API (Expand for details)
The config passed to these functions must have a key called
_target_, with the value of a fully qualified class name, class method, static method or callable.
Any additional parameters are passed as keyword arguments to the target. For convenience,
None config results in a
Your application might have an Optimizer class:
Let's add a Dataset and a Trainer class. The trainer holds a Dataset and an Optimizer instances.
With the following config, you can instantiate the whole thing with a single call:
Hydra will instantiate nested objects recursively by default.
You can override parameters for nested objects:
Disable recursive instantiation
You can disable recursive instantiation by setting
False in the config node or in the call-site
In that case the Trainer object will receive an OmegaConf DictConfig for nested dataset and optimizer instead of the instantiated objects.
Parameter conversion strategies
By default, the parameters passed to the target are either primitives (int, float, bool etc) or
OmegaConf containers (DictConfig, ListConfig). OmegaConf containers have many advantages over primitive dicts and lists but in some cases it's desired to pass a real dicts and lists (for example, for performance reasons).
You can change the parameter conversion strategy using the
_convert_ parameter (in your config or the call-site).
Supported values are:
none: Default behavior, Use OmegaConf containers
partial: Convert OmegaConf containers to dict and list, except Structured Configs.
all: Convert everything to primitive containers
Note that the conversion strategy applies to all the parameters passed to the target.