How to represent value + units in YAML?
config, yaml
Solution
I have a suggestion for an alternative to YAML. If you want to use value/unit combination for your parameters, you can try DIP serialisation language. It was designed particularly for this purpose. Syntax of DIP is very similar to Python and YAML and supports automatic unit conversions, exports to various formats and automatic generation of Sphinx and PDF documentations.
runtime
t_max float = 10 ns
timestep float = 0.01 ns
box
geometry int = 3
size
x float = 10 nm
y float = 3e7 nm
modules
heating bool = false
radiation bool = true
By the way, I am the author and I would be happy to hear your comments and suggestions for improvements. Check it out on GitHub, or PyPi.
Problem
I'm designing a new config/data format, which will be in YAML. Many of the inputs are int/float values, with associated units (e.g. liter, quart, pint, second, minute, ...). I've been searching and reading, but still can't figure out: What is the best way to associate a value and unit to a config item in YAML? Example: Say I have a list of several beverages, and (among other things), I want to input their volume. I can think of a few ways, but (at least in my opinion) none of them are really ideal: Require all volume values to be input in the same units. Forces the user to do the unit conversion him/herself, which is tedious, error-prone, and difficult to verify later, because now the quantity input differs from the original quantity listed for the beverage. (Beverages come from several different sources, each potentially using a different unit of measure.) Represent the value with a sequence of volume and units. Example: ``` volume: [ 0.5, Gallons ] ``` (A mapping would work as well, although more verbose) The sequence might be OK, but I'm not sure if I'm comfortable with it. Use two "volume" values, one for value, the other for units. Example: ``` volume_value: 0.5 volume_units: Gallons ``` I think this is a non-starter. Verbose, very loose association, error-prone. Use a string instead, and parse it in the application. Example: ``` volume: 0.5 Gallons ``` Simplest to enter, and is very easy to write a robust parser. Seems perhaps like a bit of a hack, though... Application tags: ``` volume: !gallons 0.5 ``` Not sure about this one, as I am new to YAML and don't yet have a good understanding of tags. Syntax is a little more fragile, perhaps. So, the question is: per the YAML spec, or defacto best practice/convention, is there a specific way of representing values + units? Whether it's one of the five I listed or something else, I do hope there is a "right answer", to stay within the site Question guidelines.