How to handle non-string config with Hydra?

45 Views Asked by At

Consider the following example:

from loguru import logger
import sys


logger.add(sys.stdout, level="INFO")

It is pretty simple to create a hydra config for the level parameter:

log:
  level: INFO

On the other hand, I don't know how to create a config parameter for sys.stdout? I tried to do something like:

log:
  level: INFO
  stream: sys.stdout

However, in the script:

@hydra.main(version_base=None, config_path="../config", config_name="main")
set_log(cfg: DictConfig):
  logger.add(cfg.log.stream, level=cfg.log.level)

cfg.log.stream gives the string "sys.stdout". How to solve it?

2

There are 2 best solutions below

0
Omry Yadan On

You could use OmegaConf custom resolvers for a case like this.

from omegaconf import OmegaConf
import sys

OmegaConf.register_new_resolver("sys.stdout", lambda _: sys.stdout)

c = """
  log:
    level: INFO
    stream: ${sys.stdout:_}
"""

cfg = OmegaConf.create(c)
print(cfg.log.stream)

Outputs:

<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
0
Juliana Xavier On

Maybe not the most elegant solution, but the shortest one is the resort to eval()

@hydra.main(version_base=None, config_path="../config", config_name="main")
set_log(cfg: DictConfig):
  logger.add(eval(cfg.log.stream), level=cfg.log.level)