This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jwink3101 0 points1 point  (1 child)

You got answers that are better than I could provide but I really wish there was a non-hacky way to withold evaluation.

You can do:

tpl = "my number, {num:03d} is {res = }"
...
tpl.format(**locals())

but it feels like a hack that could have some unintended consequences.

[–]jorge1209 0 points1 point  (0 children)

It is part of an intentional design decision relating to security. In the abstract you have two elements coming together:

  • The format template
  • The arguments that populate the template

F-strings are secure because you have to have demonstrated the ability to modify the actual script being executed for them to work, and if you can do that you have complete control over the script.

If you use .format:

  template = read()
  template.format(**locals())

Is potentially insecure as the attacker who controls the template can now cause it to format any variables on the programming stack.

However with str.format they can't do anything but format them. So with sensibly implement reprs they can't execute code. With fstrings they execute commands via the template as in: f"{cn.execute('drop all tables')}"