Created
March 10, 2018 15:09
-
-
Save eak24/4efa48f426ec4ecda21e8c961ed1a939 to your computer and use it in GitHub Desktop.
Converting Pint Quantities To YAML and back with YAML tags in Pint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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