Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent implicit conversion of Octal/Hex/binary to Int in PyYAML?

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 ?

like image 435
Sachin Bhat Avatar asked Oct 15 '25 15:10

Sachin Bhat


1 Answers

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)
like image 97
jdaz Avatar answered Oct 17 '25 06:10

jdaz