Search code examples
pythonconfigurationyamlfb-hydra

How to use Hydra Config alongside user-defined parameters?


Is there a way to use Hydra Config alongside other parameters?

I want some arguments to be defined in the code, and others to be read from the config file.

@hydra.main(config_path="conf", config_name="vehicle_manager")
def __init__(self, client: carla.Client, cfg: DictConfig) -> None :
  self.client = client
  self.traffic_manager = self.client.get_trafficmanager(cfg.tm_port)

The client will be provided by another module, and cfg should be read from the config file.

Is it possible to do so?


Solution

  • The current implementation of @hydra.main requires the decorated function to take just one parameter, which is the DictConfig (or ListConfig) object resulting from config composition.

    One possibility is to use the compose API which gives more flexibility to use a functional programming paradigm.

    Another possibility is to refactor your application so that the @hydra.main-decorated function takes just one parameter (i.e. cfg: DictConfig) and then have that decorated function create the carla.Client instance.

    A final possibility would be to use Hydra's instantiate API so that the carla.Client instance can be specified as a part of the cfg object.

    @hydra.main(config_path="conf", config_name="vehicle_manager")
    def app(self, cfg: DictConfig) -> None :
      assert cfg.carla_client._target_ == "carla.Client"
      client = hydra.utils.instantiate(cfg.carla_client)
      assert isinstance(client, carla.Client)
      self.client = client
      ...