link89
link89

Reputation: 1821

Is it possible to limit YAML bool value literal in python?

I am using YAML to describe some configuration that will be read by a Python tool using ruamel. The problem is I need to use string literal ON a lot and in YAML ON without quote will be treated as bool value true. I have to quote those 'ON' carefully or else the tool will throw unexpected result.

Is it possible to tell ruamel to only treat true and false as bool, and for other keywords like ON, Yes, just treat them as string literal to reduce the chance of making mistake? For this use case I don't think I have to stick to the YAML specification as there is little chance that the configuration file will be processed by others.

Upvotes: 1

Views: 445

Answers (1)

Anthon
Anthon

Reputation: 76902

I assume you are using ruamel.yaml and not some of the other packages in the ruamel. namespace. Without some code it is difficult to see what you are doing wrong, but if you use the default loader you'll get a string for loading On or on.

import sys
import ruamel.yaml

yaml_str = """\
- True
- On
- on
"""
    
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
print(data)

which gives:

[True, 'On', 'on']

If your document has a %YAML 1.1 directive, or set yaml.version = (1, 1), then On will be read as boolean:

import sys
import ruamel.yaml

yaml_str = """\
- True
- On
- on
"""
    
yaml = ruamel.yaml.YAML()
yaml.version = (1, 1)
data = yaml.load(yaml_str)
print(data)

which gives:

[True, True, True]

Upvotes: 2

Related Questions