-1

I have an exec statement to set the formatting of two variables in python 3.6. Even though the code works fine, I need to change this due to compliance issue. Please let me know how it can be done differently.

My statement: exec("{}='{}'".format(item,s))

thanks in advance for your help.

adusur
  • 1
  • 2
  • It is often a bad idea to assign variables this way and usually just storing them in a dictionary as key/value pairs is the right way to do it. What is the context? – Mark Tolonen Jul 18 '22 at 22:26

1 Answers1

0

Without knowing more:

locals()[item] = str(s)

will work for "simple" names (foo, x, etc.), but not for more complex assignments that your exec approach could handle (e.g. instance.attr)

In either case, "there must be a better way" to do what you're trying to do, but there's no context to help with that.

jedwards
  • 29,432
  • 3
  • 65
  • 92
  • From `help(locals)`: "NOTE: Whether or not updates to this dictionary will affect name lookups in the local scope and vice-versa is *implementation dependent* and not covered by any backwards compatibility guarantees.", Modifying locals is not recommended. – Mark Tolonen Jul 18 '22 at 22:27