Search code examples
python-3.xyamlpyyaml

Error on load if YAML key has no value (instead of None)?


I have a YAML file with an unknown number of "layers", so when I load it to a Python dictionary it becomes a nested dictionary.

I don't want to allow keys without values in the YAML file. I'd like to either:

  • cause errors during yaml.load() if there are missing values, or
  • identify all None values within the resulting nested dictionary.

 

import yaml
with open(input_path, "r") as yaml_file:
    my_dict = yaml.load(yaml_file)

Solution

  • You can redefine the Parser's process_empty_scalar method to raise an error:

    import yaml
    
    yaml_str = """\
    - 1
    - - 2
      -
      - 3
    """
    
    def pes(*args, **kw):
        raise NotImplementedError
    
    yaml.parser.Parser.process_empty_scalar = pes
    
    data = yaml.safe_load(yaml_str)
    
    print(data)
    

    The above raises an error, if you comment out the assignment to .process_empty_scalar it parses correct.

    Please note:

    • layers in YAML do not necessarily mean python dicts will be formed
    • you are using .load which is documented to be unsafe and almost guaranteed to be inappropriate.