Search code examples
pythonyamlpython-3.6f-string

Leverage Python f-strings with Yaml files?


If I have a yaml file containing a string with the bracket notation {} used in partnership with python f-strings, how might a leverage the f-string interpolation here? Take for example this simple yaml file:

# tmp.yaml
k1: val1
k2: val2 as well as {x}

If x = 'val3', I would like the value of the k2 to reflect val2 as well as val3

# app.py
x = 'val3'
with open('tmp.yaml', 'rt') as f:
    conf = yaml.safe_load(f)

print(conf)
{'k1': 'val1', 'k2': 'val2 as well as {x}'}

This could be accomplished pretty easily with format strings...

print(conf['k2'].format(x=x))
val2 as well as val3

But how to do the same with f-strings?


Solution

  • I found that jinja2 provides the easiest solution to this problem.

    Source yaml file:

    # tmp.yaml
    k1: val1
    k2: val2 as well as {{ x }}
    

    Read the file and render using jinja templating:

    with open('tmp.yaml', 'rt') as f:
        conf = f.read().rstrip()
    
    print(conf)
    # 'k1: val1\nk2: val2 as well as {{ x }}'
    
    import jinja2
    template = Template(conf)
    conf = template.render(x='val3')
    config = yaml.safe_load(conf)
    
    print(config)
    # {'k1': 'val1', 'k2': 'val2 as well as val3'}