Skip to content

Commit

Permalink
modify the Dumper subclass state instead of the global yaml state. na…
Browse files Browse the repository at this point in the history
  • Loading branch information
davemfish committed Nov 5, 2024
1 parent a54bd73 commit 1298eb7
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/geometamaker/utils.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
import yaml


def represent_str(dumper, data):
def _represent_str(dumper, data):
scalar = yaml.representer.SafeRepresenter.represent_str(dumper, data)
if len(data.splitlines()) > 1:
scalar.style = '|' # literal style, newline chars will be new lines
return scalar


# Patch the default string representer so that it uses
# a literal block style when the data contain newline characters
yaml.SafeDumper.add_representer(str, represent_str)
class _SafeDumper(yaml.SafeDumper):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Patch the default string representer to use a literal block
# style when the data contain newline characters
self.add_representer(str, _represent_str)

# https://stackoverflow.com/questions/13518819/avoid-references-in-pyyaml
class _NoAliasDumper(yaml.SafeDumper):
"""Keep the yaml human-readable by avoiding anchors and aliases."""

# https://stackoverflow.com/questions/13518819/avoid-references-in-pyyaml
def ignore_aliases(self, data):
"""Keep the yaml human-readable by avoiding anchors and aliases."""
return True


def yaml_dump(data):
return yaml.dump(
data,
allow_unicode=True,
Dumper=_NoAliasDumper)
Dumper=_SafeDumper)

0 comments on commit 1298eb7

Please sign in to comment.