Search code examples
pythonpython-exec

Python: Is exec always bad practice and if so why not deprecated


Can someone think of an example with good practice that uses exec?

If there is always a more efficient and secure way to replace exec, why python doesn't deprecate exec?


Solution

  • No, eval and related tools are not always bad by any measure.

    There are a number of things that only work well when they are expressed as regular functions with regular, positional or keyword arguments (not magic *args or **keywords args). There's no way to dynamically create a function with a desired set of arguments, except with eval.

    For a good example of how this can be used, examine the implementation of collections.namedtuple. Although it would be possible to create a class factory like that without eval, but all of the functions it defines, __new__ and _replace in particular, would have useless help text, and would be a less convenient tool without it. Worse, the non-eval implementation would almost certainly be SLOWER.

    Another, more sweeping example of this exact use of eval is the fine decorator library, which generalizes this practice in a collection of tools that allow you to dynamically create functions with particular function signatures; it uses eval internally.