0

Are there practical usages of eval, exec, and ast.literal_eval? The only times that I have seen them in actual usage is if something like a python object is saved into a file and isn't pickled or anything else.

What would be some actual non-trivial use cases of using these functions? The only example I was able to find in the docs was:

>>> x = 1
>>> eval('x+1')
2
CypherX
  • 7,019
  • 3
  • 25
  • 37
  • 1
    Any time you want to dynamically execute python code, of course. – juanpa.arrivillaga Oct 21 '19 at 22:53
  • See [Are questions asking for further use cases for "feature x" on-topic?](https://meta.stackoverflow.com/questions/272993/are-questions-asking-for-further-use-cases-for-feature-x-on-topic) -- such questions are almost always too broad to be permissible here. – Charles Duffy Oct 21 '19 at 22:54
  • ...that said, [Using Python's `eval()` vs `literal_eval()`?](https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) answers at least a significant corner of this question; and [What's the difference between `eval()`, `exec()` and `compile()`?](https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile) answers another. That we have multiple questions that (in some cases quite comprehensively) handle subsets is another strong signal that the question is overbroad. – Charles Duffy Oct 21 '19 at 22:56
  • (BTW, note that the latter of those is quite old; the rules around what's considered on-topic/in-scope have changed over time). – Charles Duffy Oct 21 '19 at 22:57
  • For a concrete example, several answers the question [Read data from CSV file and transform from string to correct data-type, including a list-of-integer column](https://stackoverflow.com/questions/11665628/read-data-from-csv-file-and-transform-from-string-to-correct-data-type-includin) make use of `ast.literal_eval()`. Older versions of the built-in `namedtuples` function also used it to dynamically create a class. The author also posted a [recipe](https://code.activestate.com/recipes/500261-named-tuples/) for it. – martineau Oct 21 '19 at 23:07

1 Answers1

0

eval and exec are for dynamically executing simple Python expressions or more complex statements (respectively).

So, one practical example from the standard library, collections.namedtuple uses exec to dynamically define a __new__ method for the tuple subclass being returned:

# Create all the named tuple methods to be added to the class namespace

s = f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))'
namespace = {'_tuple_new': tuple_new, '__name__': f'namedtuple_{typename}'}
# Note: exec() has the side-effect of interning the field names
exec(s, namespace)
__new__ = namespace['__new__']
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
    __new__.__defaults__ = defaults

This sometimes makes sense, however, this is often abused by inexperience programmers to write unnecessarily dynamic code, e.g. dynamically creating a bunch of variables, when they should have used a list or a dict (or some other container) instead.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • Note, it used to be that essentially the entire class definition was dynamically executed, but this slowed things down, enough so that a new implementation was added, using `exec` only to define `__new__` – juanpa.arrivillaga Oct 21 '19 at 23:13