Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

As explained in other questions, eval/exec are considered bad practice because they're generally abused to do a task where they aren't needed, leading to potential security issues and generally bad programming.

There are, however, valid uses for these mechanisms, and they expose important functionality that is not available elsewhere - executing arbitrary code at runtime.

Imagine, for example, that you want write a application that updates itself. You could fetch a script from a remote URL that runs with exec and updates your application to the latest version. While doing something like that, by itself, would pose a great security hazard, it's not hard to make the process secure through the use of digital signatures.

You can find another common use in the code module source: executing code input from the user at runtime for debugging purposes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top