Skip to content

Instantly share code, notes, and snippets.

@rwarren
Last active September 13, 2021 15:14
Show Gist options
  • Save rwarren/af4bec2a7d12d6dbc45550781896e3b1 to your computer and use it in GitHub Desktop.
Save rwarren/af4bec2a7d12d6dbc45550781896e3b1 to your computer and use it in GitHub Desktop.
Getting PyYaml's `yaml.safe_load` to support `pathlib.Path`
import pathlib
import yaml
def _path_representer(dumper, data):
return dumper.represent_scalar("!Path", str(data))
def _path_constructor(loader, node):
value = loader.construct_scalar(node)
return pathlib.Path(value)
yaml.add_multi_representer(pathlib.Path, _path_representer)
yaml.SafeLoader.add_constructor("!Path", _path_constructor)
d = dict(
p1 = pathlib.Path("/foo/bar"),
p2 = pathlib.Path("/baz/qux"),
s1 = "this is just a string",
)
dumped = yaml.dump(d)
loaded = yaml.safe_load(dumped)
print(f"dumped:\n---\n{dumped}")
print(f"loaded:\n---\n{loaded}")
# dumped:
# ---
# p1: !Path '/foo/bar'
# p2: !Path '/baz/qux'
# s1: this is just a string
#
# loaded:
# ---
# {'p1': PosixPath('/foo/bar'), 'p2': PosixPath('/baz/qux'), 's1': 'this is just a string'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment