fb-hydraomegaconf

How to use callable targets with dataclass arguments in Hydra?


Is it possible to define a target using Structured Configs to avoid redefining all the parameters?

def good(config: Config):
    pass

def bad(param1, param2):
    pass

@dataclass
class Config:
    param1
    param2
    _target_: Any = good
    # _target_: Any = bad
    # _target_: str = 'Config.also_good'

    def also_good(self):
        pass

What type annotation should I use for _target_ in case of a class, function, or method? When I used Any I got

omegaconf.errors.UnsupportedValueType: Value 'function' is not a supported primitive type
    full_key: _target_

Solution

  • The _target_ type should be str. Here is an example using the instantiate API with a structured config:

    # example.py
    from dataclasses import dataclass
    
    from hydra.utils import instantiate
    
    
    def trgt(arg1: int, arg2: float):
        print(f"trgt function: got {arg1}, {arg2}")
        return "foobar"
    
    
    @dataclass
    class Config:
        _target_: str = "__main__.trgt"  # dotpath describing location of callable
        arg1: int = 123
        arg2: float = 10.1
    
    
    val = instantiate(Config)
    print(f"Returned value was {val}.")
    

    Running the script:

    $ python example.py
    trgt function: got 123, 10.1
    Returned value was foobar.
    

    Notes:

    References: