Hydra: How to express None in config files?
Asked Answered
P

3

10

I have a very simple Python script:

import hydra
from omegaconf import DictConfig, OmegaConf


@hydra.main(version_base="1.3", config_path=".", config_name="config")
def main(cfg: DictConfig) -> None:
    if cfg.benchmarking.seed_number is None: 
        raise ValueError()

if __name__ == "__main__": 
    main()

And here the config file:

benchmarking: 
  seed_number: None 

Unfortunately, the Python script does not raise an error. Instead, when I print the type of cfg.benchmarking.seed_number, it is str. How can I pass None instead?

Proprietary answered 27/6, 2023 at 18:24 Comment(2)
What value is cfg.benchmarking.seed_number being set to? "None" or something else? Does hydra document how it's config (yaml?) file is parsed?Mariettemarigold
You should use the word 'null' instead of None in the configuration fileBallottement
H
16

Try null:

benchmarking: 
  seed_number: null
Harriet answered 27/6, 2023 at 20:25 Comment(1)
Thanks - I've been using this stuff for years and didn't think you could!Kellar
P
3

In YAML format, it represents None as a string ("None").

To pass None as the value instead, you can replace it with !!null

benchmarking:
seed_number: !!null

Using !!null in the YAML configuration, it explicitly represents a null value.

But as this configuration is loaded into the Python, cfg.benchmarking.seed_number will be None instead of a string.

Pupillary answered 27/6, 2023 at 23:12 Comment(0)
A
0

As mentioned at https://omegaconf.readthedocs.io/en/latest/grammar.html

Other special keywords (also case-independent): null, true, false, NULL, True, fAlSe. IMPORTANT: None is not a special keyword and will be parsed as an unquoted string, you must use the null keyword instead (as in YAML).

in my Hydra setup both null and !!null worked. !!null is more distinctive to the developer eye :) .

Audio answered 13/6 at 12:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.