Lucas
Lucas

Reputation: 3725

Performing arithmetic operation in YAML?

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?

Upvotes: 36

Views: 40280

Answers (3)

Walid Bousseta
Walid Bousseta

Reputation: 1469

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

Upvotes: 0

Art Vandelay
Art Vandelay

Reputation: 180

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.

Upvotes: 9

Rafael Almeida
Rafael Almeida

Reputation: 2397

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).

Upvotes: 19

Related Questions