Performing arithmetic operation in YAML?

Question:

Sometimes I have to specify the time (in seconds) in the configuration file, and it’s quite annoying to write exact seconds amount – instead I would like to perform arithmetics so I could use:

some_time: 1 * 24 * 60 * 60

instead of exact:

some_time: 86400

Unfortunately, while using this line: some_time: 1 * 24 * 60 * 60, it will treat that configuration line as a string. Of course, I can use – eval(config['some_time']) but I am rather wondering if that is possible to perform arithmetics in YAML?

Asked By: Lucas

||

Answers:

I don’t think there is. At least not on spec (http://yaml.org/spec/1.2/spec.html). People add non-official tags to yaml (and wikipedia seems to say there’s proposal for a yield tag, though they don’t say who proposed or where: http://en.wikipedia.org/wiki/YAML#cite_note-16), but nothing like you need seems to be available in pyyaml.

Looking at pyyaml specific tags there doesn’t seem to be anything of interest. Though !!timestamp '2014-08-26' may be handy in some of your scenarios (http://pyyaml.org/wiki/PythonTagScheme).

Answered By: Rafael Almeida

This can be accomplished by using the Python-specific tags offered by PyYAML, i.e.:

!!python/object/apply:eval [ 1 * 24 * 60 * 60 ]

As demonstrated in the below:

In [1]: import yaml                                                                                                                             

In [2]: yaml.load("!!python/object/apply:eval [ 1 * 24 * 60 * 60 ]")                                                                            
Out[2]: 86400

This is, naturally, the same as performing eval(config['some_time']), but saves you from having to handle it explicitly in your program.

Answered By: Art Vandelay

I searched for a way to that, but without any success but I have used the following to work around it:

import yaml
from box import Box

file = """
data:
    train_size: 100**2
    test_size: 10**2
"""

config = Box(yaml.safe_load(file))
tr_size = eval(config.data.train_size)
# 100**2 -> 10000
ts_size = eval(config.data.test_size)
# 10**2 -> 100
Answered By: Walid Bousseta
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.