1

I have searched methods of dynamically setting local variables on the Stack Overflow and saw many suggested using setattr and didn't recommend exec() (dict() or vars() were also suggested, but the first two seem pythonic to me).

But no one tells why exec() is worse or unsafe.

Could somebody explain this?

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
Jape
  • 11
  • 5
  • 3
    How do you use `setattr` to set a local variable? – cs95 Aug 14 '17 at 05:25
  • 1
    You're comparing apples to oranges. `setattr` is used to set **_object attributes_**, not local variables. `exec` is used to dynamically execute Python code. As for why `exec` is general considered unsafe, see [here](https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided). – Christian Dean Aug 14 '17 at 05:27
  • It looks like OP is trying to have a workaround by creating an empty class Creating an object of the same ,then use setattr to set/create new attributes to that local object – Sarath Sadasivan Pillai Aug 14 '17 at 05:30
  • sorry for my ignorance, I was reading https://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name and https://stackoverflow.com/questions/8028708/dynamically-set-local-variable and referred the question title as I didn't know exact concept applied here. – Jape Aug 14 '17 at 05:31
  • Also note that dynamically creating variables is very, _very_ rarely a good idea nor necessary. Use a data structure such as a list or dictionary. – Christian Dean Aug 14 '17 at 05:32
  • @ChristianDean thanks for the advice. I also figured out that I can simply use a dictionary, but I am still curious why `exec()` is unsafe as many warned. – Jape Aug 14 '17 at 05:35
  • Maybe my question is more about why `exec()` is unsafe as you suggested. Thanks @ChristianDean – Jape Aug 14 '17 at 05:36
  • If you're sure about that, then I'll mark this duplicate. – cs95 Aug 14 '17 at 05:38
  • Thanks @cᴏʟᴅsᴘᴇᴇᴅ ! – Jape Aug 14 '17 at 05:39

0 Answers0