0

I have a certain template string in Python, e.g.:

'{a} and {b}'

and two functions, foo() and bar(). Each of them is providing a or b. I would like the template string to go first through foo() and then through bar() so that at the end of foo() and bar(), I have the full interpolation:

def foo(template):
    return template.format(a=10)


def bar(template):
    return template.format(b=20)


print(foo(bar('{a} and {b}')))
# 10 and 20
print(bar(foo('{a} and {b}')))
# 10 and 20

Is there an elegant way of doing so?

So far, I have resorted to use this as template:

'{a} and {{b}}'

which works half way, in that it will not support both foo(bar()) and bar(foo()). Additionally, the template gets harder to read.

norok2
  • 25,683
  • 4
  • 73
  • 99

1 Answers1

0

You can use a dictionary to hold the format arguments, pass that through foo() and bar() and then unpack it into the format function.

format_dictionary = {
    'a' : 'cats',
    'b' : 'dogs'
}
print('{a} and {b}'.format(**format_dictionary))
cats and dogs