Search code examples
pythonrubyyamlpyyaml

pyyaml converts mac address to number


I got this weird issue while loading a yaml file with a mac address where the address got converted to number.

>>> yaml.safe_load('abc: 11:00:00:00:00:00')
{'abc': 8553600000}
>>> yaml.safe_load('abc: 99:00:00:00:00:00')
{'abc': 76982400000}

But then I tried with following and I get answer as expected.

>>> yaml.safe_load('abc: ff:00:00:00:00:00')
{'abc': 'ff:00:00:00:00:00'}

I know solution for this which is to have the mac addresses inside quotes but I want to know reason for this behaviour.

Interestingly, I tried same data with ruby and got similar results.

EDIT

Adding new test data where it works with only numbers

>>> yaml.load('abc: 52:00:00:60:00:00')
{'abc': '52:00:00:60:00:00'}

Solution

  • pyyaml works with YAML version 1.1 which supports sexagecimal numbers, so positive integers lower than 60 separated with colons are considered as single number and you get its decimal presentation. If you want your MAC-addresses to be recognized as strings just add quotes like

    >>>yaml.safe_load('abc: "11:00:00:00:00:00"')
    {'abc': '11:00:00:00:00:00'}
    

    Also there is ruamel.yaml which seems to support YAML version 1.2, where they've got rid of sexagecimals:

    >>>import ruamel.yaml
    >>>ruamel.yaml.safe_load('abc: 11:00:00:00:00')
    {'abc': '11:00:00:00:00'}