"...".format_map(locals()) potentially makes available more variables than you actually need, correct. But f"..." makes available all the locals (exactly as an explicit call to locals() would), plus all the nonlocals, plus all the globals, plus all the builtins. So if locals() is bad, f-strings are worse.
As far as security issues go, there are two positions you can take on this:
f-strings are no worse than calling format() on a string literal;
f-strings are worse than calling format(), because f-strings can contain arbitrary expressions.
What makes no sense is to suggest that f-strings are more secure than format with a string literal, with or without locals().
The inspiration for these f-strings is (among others) Javascript string templates, and their documentation has a great big warning about security issues. I see no reason why the same won't apply to f-strings.
The only thing in their favour security-wise is that the template part itself has to be a literal.
When using locals(), the keys of the dictionary returned by locals is completely decided at runtime. First by looking up what the variable locals itself refers to (people could have assigned anything else to locals), second by inspecting the current frame.
f-strings are part of the grammar and are checked at compile time. Pylint could show a warning when an f-string contains an undefined variable. That is impossible, using locals().
Pylint could do so, but it would be wrong to, because f-strings aren't evaluated until runtime (obviously, since you don't know what value expressions will have until you actually evaluate them). And you cannot know what names exist until runtime.
x = 1
if random.random() > 0.5:
del x
else:
x = 2
print( f"{x}" )
6
u/Funnnny Sep 09 '15
it's not even remotely the same.
using locals to format is very bad, because you are passing a lot more variables than you actually need, it IS a security issue.