Skip to content

Instantly share code, notes, and snippets.

@dsoprea
Created April 1, 2022 06:51
Show Gist options
  • Save dsoprea/fcc2d8245180288985f738e08a587bdc to your computer and use it in GitHub Desktop.
Save dsoprea/fcc2d8245180288985f738e08a587bdc to your computer and use it in GitHub Desktop.
Replace tokens into YAML during load
import string
import yaml
def load_yaml(f, context=None):
if context is None:
context = {}
def string_constructor(loader, node):
t = string.Template(node.value)
value = t.substitute(context)
return value
l = yaml.SafeLoader
l.add_constructor('tag:yaml.org,2002:str', string_constructor)
token_re = string.Template.pattern
l.add_implicit_resolver('tag:yaml.org,2002:str', token_re, None)
x = yaml.load(f, Loader=l)
return x
y = """\
aa: bb
cc: dd $EE ff
"""
context = {
'EE': '123',
}
d = waw.utility.load_yaml(y, context)
print(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment