In the YAML file, I am expecting users to enter only Decimal integer values.
There are other objects in the YAML file as well. But, integer values will be specified without quotes. So, I am concerned only about the integer inputs.
Sample YAML file:
DecimalsList:
- 34
- 0432 # PyYAML converts 0432 to 287 by interpreting this as octal.
I am reading this YAML file in my python script using yamlordereddictloader
with open(yaml_file_path, 'r') as stream:
yaml_object = yaml.load(stream,
Loader=yamlordereddictloader.Loader)
This will break my application logic as it does not match the value entered in YAML file.
I want to throw an error if anything other than decimal is entered in this list.
How can I achieve this ?
Is there a way to stop this implicit conversion for integers by PyYAML ?
There may be a better way to do this, but one way is to preprocess your yaml file and remove any leading zeroes with regex:
import re
with open(yaml_file_path, 'r') as stream:
stream = re.sub(r'\b0(\d+)\b', r'\1', stream.read())
yaml_object = yaml.load(stream,
Loader=yamlordereddictloader.Loader)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With