TL;DR: Consider using eval()
I found this page because I was looking to do some simple template processing with python string functions (short of including a full blown template engine). I was searching for how to set local variables, and that's how I got here.
My problem began with a simple template:
Hello, {name}
The way I populated this template was this way:
def populate(template,variables):
return template.format(**variables)
And so this would work:
values = {
'name' : 'Stack Overflow'
}
my_template = "Hello, {name}"
print( populate( my_template , values ) )
# output
Hello, Stack Overflow
But then things went south fast. I tried a new template where I only wanted the first word:
Now my template was this: "Hello, {name.split()[0]}"
and this code got an error.
values['name'] = "Stack Overflow"
my_template = "Hello, {name.split()[0]}"
print( populate( my_template , values )
# output (well, stderr)
AttributeError: 'str' object has no attribute 'split()'. Did you mean: 'split'?
And then I learned that the format function doesn't work the way I want it. You can't pass arbitrary code to it. You need to pass it formatting stuff. And so I tried a different solution. I coded populate
to use eval
and an f-string instead of format
. An f-string (unlike format) allows for python code in the curly brace interpolation. So an f-string like this `f"Hello, {name.split()[0]}" does work. Let's just see the code for this small part (so you don't have to leave this post to figure out f-string):
name = "Stack Overflow"
print(f"Hello, {name.split()[0]}")
# Output:
Hello, Stack
Now I just had to use an f-string. So I used eval
. My new populate is this:
def populate(template,variables):
return eval(f'f"{template}"')
But when I ran the program again, I got this error:
NameError: name 'name' is not defined
I should point out that an f-string is able to populate the string with any global or local variable in scope. To fix my issue, I could change my template to "Hello, {variables['name']}"
since variables
is definitely in scope. This is really bad approach because now the template writer has to know about a the variables
dictionary. Rather, I want to make every key available in the variables
dictionary available to the template author, as I had before with format(**variables)
.
To solve my problem, I wanted to set local variables based on the content of the variables
dictionary passed to the populate()
function.
I tried this:
locals() = variables
And that didn't work:
locals() = variables
^^^^^^^^
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
And then I tried this and this worked:
def populate(template,variables):
for k,v in variables.items():
locals()[k] = v
return eval(f'f"{template}"')
values = {
'name' : 'Stack Overflow'
}
my_template = "Hello, {name.split()[0]}"
print( populate( my_template , values ) )
And so the first take away is that you can create local variables in a function (or globals for that matter) by setting a key value pair in the locals() dictionary.
In the case of eval
, the second and third parameters allow you to pass in local and global variables, and so you could simplify the populate function to just this:
def populate(template,variables):
return eval(f'f"{template}"',variables)
The above is how I used eval
to do f-string population (or simplistic template evaluation). But eval
can also be used to provide variable variables.
locals
will not affect local namespaces in CPython. Which is another reason not to do it.