Created
April 1, 2022 06:51
-
-
Save dsoprea/fcc2d8245180288985f738e08a587bdc to your computer and use it in GitHub Desktop.
Replace tokens into YAML during load
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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