1

I have been looking around StackOverflow for Python dynamic variable naming. And though I now know how much better it is to use a dictionary to store my dynamic objects. But I've seen more than once people saying that there IS a way to do it, and at the same time saying it's dangerous and I SHOULDN'T use it. I wanted to ask why is it dangerous, and why is it a thing even? When DO you use it? What is it for?

This is much more out of curiosity than a problem to solve. But it's a question nonetheless. Thanks for the time.

  • 5
    `exec` and `eval` are only dangerous on non-trusted input. They are dangerous on non-trusted input because *they execute arbitrary code*, and thus are a security hole. Suppose `x = input("what do you want to do"); exec(x)`, and suppose the user enters `import os; os.system('echo "this could be worse"')`... – juanpa.arrivillaga Apr 20 '20 at 06:06
  • 3
    Here's [nedbatchelder's blog post about `eval`](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) – Ch3steR Apr 20 '20 at 06:09
  • On trusted input, it's not a security risk, but *very often* it is simply the wrong tool. – juanpa.arrivillaga Apr 20 '20 at 06:10
  • 1
    re. dynamic names, with `setattr` and similar, there are not that many great reasons to exec/eval. also, consider that non-trusted is rather broad. if you were to load a data file via pickle, for example, is it possible that someone wrote with access to the file system wrote malicious stuff into that file? sure, that kind of access would result in a compromise, *somewhere*. but that compromise point is now your app with its user privileges... and the breach report details will showcase that. – JL Peyret Apr 20 '20 at 06:13
  • 1
    Besides the above mention security problems, it's also a style issue. Python provides numerous introspection and dynamic programming features that make `eval` and `exec` mostly unnecessary. – Keith Apr 20 '20 at 06:20
  • 1
    That makes sense actually. I was thinking on how dangerous they could really be. And thanks to Sheri's comment I understand a little more on how they work. It's real interesting stuff, and yeah I don't think I'd use it for something as simple as my current personal projects are. Thanks for the comments though, I appreciate your time. – BangTheBanger Apr 20 '20 at 06:26
  • see if [ast.literal_eval](https://docs.python.org/3/library/ast.html#ast.literal_eval) covers some of the residual requirements you may have. – JL Peyret Apr 20 '20 at 06:28

0 Answers0