Skip to content

Instantly share code, notes, and snippets.

@eak24
Created March 10, 2018 15:09
Show Gist options
  • Save eak24/4efa48f426ec4ecda21e8c961ed1a939 to your computer and use it in GitHub Desktop.
Save eak24/4efa48f426ec4ecda21e8c961ed1a939 to your computer and use it in GitHub Desktop.
Converting Pint Quantities To YAML and back with YAML tags in Pint
import pint
import yaml
u = pint.UnitRegistry(system='mks', autoconvert_offset_to_baseunit=True)
def units_representer(dumper, data):
return dumper.represent_scalar(u'!u', str(data))
yaml.add_representer(u.Quantity, units_representer)
def units_constructor(loader, node):
value = loader.construct_scalar(node)
mag, units = value.split(' ')
return u.Quantity(float(mag), units)
yaml.add_constructor(u'!u', units_constructor)
q = 5*u.meter
print("The raw pint quantity:", q)
#The raw pint quantity: 5 meter
yaml_string = yaml.dump(q)
print("The resulting yaml:", yaml_string)
#The resulting yaml: !u '5 meter'
q_reborn = yaml.load(yaml_string)
print("The reloaded quantity with some math done on it", q_reborn**2)
#The reloaded quantity with some math done on it 25.0 meter ** 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment