1

I read a formatting message from database, and I want to fill message parameters from a dictionary.

The problem is where I got a mixed parameter that need calculation.

data = {"p1": 10, "p2": 8}
msg = "user point is {p1+p2}" # read from database
print(msg.format_map(data))

How can I handle this?

safineh
  • 80
  • 9
  • There are trivial solutions that involve `eval`. But this is very likely to be a no-starter when dealing with exogenous inputs such as those that a database may provide. – keepAlive May 09 '22 at 20:36

1 Answers1

1

⚠️ Do not rely on the following if you do not know what 1) “dynamic evaluation” exactly means and 2) what are the exact security risks (e.g. *) you are taking by doing so. ⚠️

>>> eval(f'f"{msg}"', None, data)
'user point is 18'
keepAlive
  • 6,369
  • 5
  • 24
  • 39