From 3cf5a7fc4217da0c58148f087924effe9ad63566 Mon Sep 17 00:00:00 2001 From: Julian Knauer Date: Tue, 28 Apr 2020 21:25:13 +0200 Subject: [PATCH] PYYAML Constructor --- content/posts/easy-yaml-include-tag.md | 42 +++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/content/posts/easy-yaml-include-tag.md b/content/posts/easy-yaml-include-tag.md index d514f2c..6357b67 100644 --- a/content/posts/easy-yaml-include-tag.md +++ b/content/posts/easy-yaml-include-tag.md @@ -1,6 +1,46 @@ --- title: "Easy pyyaml '!include' Tag" date: 2020-04-28T20:59:26+02:00 -draft: true --- +# Easy pyymal file inclusion + +YAML does not support file inclusion. If this feature is needed, it is necessary to write your own constructor to support a new tag like `!include`. + +## Example YAML files + +**foo.yaml:** +```yaml +hello: !include bar.yaml +``` + +**bar.yaml:** +```yaml +'world' +``` + +**resulting yaml:** +```yaml +hello: 'world' +``` + +## Example code + +```python +import yaml + + +def include_constructor(loader, node): + filename = node.value + include = yaml.load(open(filename, 'r'), Loader=yaml.SafeLoader) + return include + + +Loader = yaml.CLoader +Loader.add_constructor(u'!include', include_constructor) + + +yaml_data = yaml.load(open('foo.yaml', 'r'), Loader=yaml.CLoader) +``` + +KTHXBYE.