From 07876cf64ed27a2b971cd23372784796d33d0ffe Mon Sep 17 00:00:00 2001 From: Max Liu Date: Fri, 1 Mar 2019 11:21:03 -0500 Subject: [PATCH] Minor improvements to yaml dumping for ArkaneSpecies Provide file stream directly to yaml.dump Remove optional Dumper argument and associated imports Add str representer to dump multiline strings as block literals --- arkane/common.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/arkane/common.py b/arkane/common.py index be49a1af3c..e8ab2c8f7b 100644 --- a/arkane/common.py +++ b/arkane/common.py @@ -35,10 +35,6 @@ import string import yaml -try: - from yaml import CDumper as Dumper, CLoader as Loader, CSafeLoader as SafeLoader -except ImportError: - from yaml import Dumper, Loader, SafeLoader from rmgpy.rmgobject import RMGObject from rmgpy import __version__ @@ -61,6 +57,16 @@ ################################################################################ +# Add a custom string representer to use block literals for multiline strings +def str_repr(dumper, data): + if len(data.splitlines()) > 1: + return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') + return dumper.represent_scalar('tag:yaml.org,2002:str', data) + + +yaml.add_representer(str, str_repr) + + class ArkaneSpecies(RMGObject): """ A class for archiving an Arkane species including its statmech data into .yml files @@ -206,7 +212,7 @@ def save_yaml(self, path): ''.join(c for c in self.label if c in valid_chars) + '.yml') full_path = os.path.join(path, filename) with open(full_path, 'w') as f: - f.write(yaml.dump(data=self.as_dict(), Dumper=Dumper)) + yaml.dump(data=self.as_dict(), stream=f) logging.debug('Dumping species {0} data as {1}'.format(self.label, filename)) def load_yaml(self, path, species, pdep=False):