{"id":85,"date":"2023-04-02T01:29:25","date_gmt":"2023-04-02T01:29:25","guid":{"rendered":"https:\/\/www.w3computing.com\/articles\/?p=85"},"modified":"2023-08-23T16:22:34","modified_gmt":"2023-08-23T16:22:34","slug":"dynamic-code-generation-execution-pythons-exec-eval","status":"publish","type":"post","link":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/","title":{"rendered":"Dynamic Code Generation &#038; Execution with Python&#8217;s exec and eval"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In the field of programming, the power of flexibility and adaptability cannot be overstated. One such powerful concept is dynamic code generation and execution, a process that provides programs with the ability to create and execute code on-the-fly, thereby enabling unparalleled flexibility in how they operate. This technique, a prominent feature in many programming languages, allows the code to write and execute other pieces of code, bringing an additional layer of dynamism and functionality to the system.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Python, renowned for its simplicity and efficiency, is not left out of this concept. The language offers two native functions &#8211; <code>exec<\/code> and <code>eval<\/code>, which allow for dynamic code execution and evaluation, respectively. The <code>exec<\/code> function is used to dynamically run Python program which can be a string or object code. On the other hand, <code>eval<\/code> parses the expression passed to it and executes python code within the program. These two powerful tools can significantly enhance the efficiency of Python programs, allowing them to adapt and evolve based on their input and environment.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This article is tailored for intermediate to advanced Python developers, who already possess a firm understanding of Python syntax and are comfortable with concepts such as functions, loops, and classes. It is not recommended for absolute beginners, as a solid grasp of Python&#8217;s basics is essential to comprehend and utilize <code>exec<\/code> and <code>eval<\/code> effectively. As we delve deeper, we will provide practical code examples and real-life scenarios to better illustrate the usage and application of these functions, and ensure a robust, hands-on understanding. Let&#8217;s dive into the power of dynamic code generation and execution with Python&#8217;s <code>exec<\/code> and <code>eval<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Overview of <code>exec<\/code> and <code>eval<\/code> functions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Python, in its vast expanse of built-in functions and capabilities, provides two unique functions\u2014<code>exec<\/code> and <code>eval<\/code>. These functions bring dynamic code execution and evaluation into the Python programming world, offering a multitude of capabilities that otherwise would be challenging to achieve.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Definition of <code>exec<\/code> and <code>eval<\/code> functions in Python<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><code>exec<\/code>:<\/strong> The <code>exec<\/code> function is a built-in Python function used to execute dynamically created programmable strings. <code>exec<\/code> takes in a single argument, which can be a string, an object code, or a callable Python object. The string or code is then executed as a Python program, allowing Python scripts to generate and run other Python scripts during execution.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><code>eval<\/code>:<\/strong> The <code>eval<\/code> function, on the other hand, evaluates a Python expression that&#8217;s been passed to it as a string. The expression can be a Python statement, or a code object. The function then parses the expression, executes it, and returns the result.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Difference between <code>exec<\/code> and <code>eval<\/code><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The key difference between <code>exec<\/code> and <code>eval<\/code> lies in their purpose and their return values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While both functions execute Python code dynamically, <code>eval<\/code> is used for simple expressions and returns the result of the evaluated expression. On the other hand, <code>exec<\/code> can handle complex code blocks with multiple lines of code, but it does not return any result. In simple terms, <code>eval<\/code> evaluates a single dynamically provided expression and returns its value, while <code>exec<\/code> executes dynamically provided code but does not return anything.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Additionally, <code>exec<\/code> can alter the state of the program by changing the values of variables or even defining new ones, whereas <code>eval<\/code> is purely for evaluating an expression and getting a result, without any side effects on the program state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example of simple usage of <code>exec<\/code> and <code>eval<\/code><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s look at basic examples of <code>exec<\/code> and <code>eval<\/code> in action:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><code>exec<\/code>:<\/h4>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">code = <span class=\"hljs-string\">\"\"\"\ndef say_hello(name):\n    return f'Hello, {name}!'\n\"\"\"<\/span>\n\nexec(code)\nprint(say_hello(<span class=\"hljs-string\">'World'<\/span>))  <span class=\"hljs-comment\"># Prints: Hello, World!<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above snippet, a multi-line Python code is defined as a string and passed to the <code>exec<\/code> function, which then executes the code, defining a new function <code>say_hello<\/code>. This function is later invoked to print a greeting.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><code>eval<\/code>:<\/h4>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">expression = <span class=\"hljs-string\">\"2 * 3 + 5\"<\/span>\nresult = eval(expression)\nprint(result)  <span class=\"hljs-comment\"># Prints: 11<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this <code>eval<\/code> example, a string containing a simple arithmetic expression is evaluated, and the result (11) is printed out.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both <code>exec<\/code> and <code>eval<\/code> serve as powerful tools for enhancing the dynamism and functionality of Python programs. However, their usage requires careful consideration and good understanding of their implications, which we will further explore in the subsequent sections.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Deep Dive into <code>exec<\/code> function<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>exec<\/code> function is an integral part of Python&#8217;s capabilities, enabling the dynamic execution of Python programs. With <code>exec<\/code>, you can create and run code that didn&#8217;t exist when your script started, or that&#8217;s not known until runtime. Let&#8217;s delve deeper into the function&#8217;s syntax, practical examples, and advanced use cases.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Syntax and Parameters of <code>exec<\/code><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The syntax for the <code>exec<\/code> function is as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">exec(object&#91;, globals&#91;, locals]])<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>object<\/strong>: This is a mandatory parameter that can be a string, an object code, or a callable Python object. It contains the code to be executed.<\/li>\n\n\n\n<li><strong>globals<\/strong>: This is an optional parameter representing a dictionary containing global parameters. If provided, it must be a dictionary.<\/li>\n\n\n\n<li><strong>locals<\/strong>: This is another optional parameter, a dictionary that contains local parameters for the code. If provided, it must be a dictionary.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If both <code>globals<\/code> and <code>locals<\/code> are omitted, the code executes in the current scope. If <code>globals<\/code> is provided but <code>locals<\/code> is omitted, <code>locals<\/code> defaults to <code>globals<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Practical Examples of <code>exec<\/code> with Code Samples<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example that demonstrates the basic usage of the <code>exec<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Define a string with Python code<\/span>\ncode_string = <span class=\"hljs-string\">\"\"\"\ndef greet(name):\n    print(f'Hello, {name}!')\n\"\"\"<\/span>\n\n<span class=\"hljs-comment\"># Execute the code string<\/span>\nexec(code_string)\n\n<span class=\"hljs-comment\"># Call the newly defined function<\/span>\ngreet(<span class=\"hljs-string\">'Alice'<\/span>)  <span class=\"hljs-comment\"># Outputs: Hello, Alice!<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, <code>exec<\/code> is used to dynamically define a new function <code>greet<\/code>, which is then called with the argument &#8216;Alice&#8217;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>exec<\/code> function can also be used with the <code>globals<\/code> and <code>locals<\/code> parameters. Let&#8217;s see how:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Define a string with Python code<\/span>\ncode_string = <span class=\"hljs-string\">\"\"\"\nresult = a + b\n\"\"\"<\/span>\n\n<span class=\"hljs-comment\"># Define global and local parameters<\/span>\nglobal_parameters = {<span class=\"hljs-string\">'a'<\/span>: <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-string\">'b'<\/span>: <span class=\"hljs-number\">10<\/span>}\nlocal_parameters = {}\n\n<span class=\"hljs-comment\"># Execute the code string<\/span>\nexec(code_string, global_parameters, local_parameters)\n\n<span class=\"hljs-comment\"># Print the result<\/span>\nprint(local_parameters&#91;<span class=\"hljs-string\">'result'<\/span>])  <span class=\"hljs-comment\"># Outputs: 15<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, <code>exec<\/code> is used to execute a code string that performs an addition operation. The variables <code>a<\/code> and <code>b<\/code> are provided through the <code>globals<\/code> dictionary, and the result of the operation is stored in the <code>locals<\/code> dictionary.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Advanced Use-Cases and Caveats<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>exec<\/code> function is extremely powerful and offers a wide range of possibilities for dynamically creating and executing code. For instance, you could use <code>exec<\/code> to build a flexible system that executes user-defined code (with proper precautions), or to dynamically import modules and utilize their functions based on runtime conditions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, it&#8217;s important to remember that with great power comes great responsibility. The <code>exec<\/code> function should be used sparingly and with great caution. Executing dynamically generated code can introduce a number of potential issues, including security vulnerabilities if the input isn&#8217;t properly sanitized, and increased debugging complexity due to the dynamic nature of the code. It&#8217;s also generally considered poor style to rely heavily on <code>exec<\/code> for things that could be accomplished with Python&#8217;s standard static syntax.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Deep Dive into <code>eval<\/code> function<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>eval<\/code> function is another dynamic execution function provided by Python, primarily used to evaluate simple Python expressions. Despite its simplicity, <code>eval<\/code> is a flexible tool that can significantly enhance the interactivity and adaptability of Python applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Syntax and Parameters of eval<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The syntax of the <code>eval<\/code> function in Python is:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">eval(expression&#91;, globals&#91;, locals]])<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>expression<\/strong>: This is a mandatory parameter, which should be a string parsed as a Python expression.<\/li>\n\n\n\n<li><strong>globals<\/strong>: This optional parameter is a dictionary containing global variables. If provided, it must be a dictionary.<\/li>\n\n\n\n<li><strong>locals<\/strong>: This optional parameter is a dictionary containing local variables. If provided, it must be a dictionary.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Similar to <code>exec<\/code>, when both <code>globals<\/code> and <code>locals<\/code> are omitted, the expression is executed in the current scope. If <code>globals<\/code> is provided but <code>locals<\/code> is omitted, <code>locals<\/code> defaults to <code>globals<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Practical Examples of <code>eval<\/code> with Code Samples<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example illustrating the basic usage of the <code>eval<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Define a string with a Python expression<\/span>\nexpression = <span class=\"hljs-string\">\"2 + 3 * 4\"<\/span>\n\n<span class=\"hljs-comment\"># Evaluate the expression<\/span>\nresult = eval(expression)\n\n<span class=\"hljs-comment\"># Print the result<\/span>\nprint(result)  <span class=\"hljs-comment\"># Outputs: 14<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, <code>eval<\/code> is used to evaluate a string that contains a simple arithmetic expression.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>eval<\/code> function can also be used with the <code>globals<\/code> and <code>locals<\/code> parameters. Let&#8217;s see an example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Define a string with a Python expression<\/span>\nexpression = <span class=\"hljs-string\">\"a + b\"<\/span>\n\n<span class=\"hljs-comment\"># Define global and local parameters<\/span>\nglobal_parameters = {<span class=\"hljs-string\">'a'<\/span>: <span class=\"hljs-number\">5<\/span>}\nlocal_parameters = {<span class=\"hljs-string\">'b'<\/span>: <span class=\"hljs-number\">10<\/span>}\n\n<span class=\"hljs-comment\"># Evaluate the expression<\/span>\nresult = eval(expression, global_parameters, local_parameters)\n\n<span class=\"hljs-comment\"># Print the result<\/span>\nprint(result)  <span class=\"hljs-comment\"># Outputs: 15<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, <code>eval<\/code> is used to evaluate an expression that includes the variables <code>a<\/code> and <code>b<\/code>, which are provided through the <code>globals<\/code> and <code>locals<\/code> dictionaries.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Advanced Use-Cases and Caveats<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>eval<\/code> function can be used in various advanced scenarios, such as evaluating mathematical expressions entered by users, or parsing and evaluating data received in string format.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, as with <code>exec<\/code>, caution must be exercised when using <code>eval<\/code>. Given that it evaluates Python expressions from strings, it can pose a serious security risk if the input isn&#8217;t thoroughly validated. Malicious code can be executed if <code>eval<\/code> is used on unsanitized user inputs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Additionally, the <code>eval<\/code> function can make debugging more difficult due to its dynamic nature, and it can also lead to poor programming practices if overused.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Security Considerations with <code>exec<\/code> and <code>eval<\/code><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">While <code>exec<\/code> and <code>eval<\/code> offer significant flexibility in Python programming, they also come with potential security risks if misused. This section delves into these risks and provides best practices and alternatives for safely utilizing these functions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Potential Security Risks of Using <code>exec<\/code> and <code>eval<\/code><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The most significant security risk with <code>exec<\/code> and <code>eval<\/code> arises when these functions are used to execute or evaluate code or expressions derived from untrusted or unsanitized sources, such as user inputs or data received over the network. These functions can execute arbitrary Python code, which means that an attacker could potentially execute malicious code, leading to data leaks, unauthorized data modification, or even complete system takeover.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For instance, an expression like <code>eval(input())<\/code> or <code>exec(input())<\/code> can be exploited by an attacker to perform arbitrary operations, like file deletion (<code>eval(\"__import__('os').system('rm -rf \/')\")<\/code>), which would delete all files in the system if the Python script has sufficient permissions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practices for Safely Using <code>exec<\/code> and <code>eval<\/code><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Given the potential security risks, here are some best practices for safely using <code>exec<\/code> and <code>eval<\/code>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Avoid Unnecessary Usage<\/strong>: Avoid using <code>exec<\/code> and <code>eval<\/code> whenever possible, especially when there are safer alternatives that achieve the same result.<\/li>\n\n\n\n<li><strong>Never Use with Untrusted Input<\/strong>: Never use <code>exec<\/code> or <code>eval<\/code> with unsanitized or untrusted inputs. This can open the door for code injection attacks.<\/li>\n\n\n\n<li><strong>Limit Scope<\/strong>: If you must use these functions, limit their scope by passing empty dictionaries to the <code>globals<\/code> and <code>locals<\/code> parameters. This will prevent the executed code from accessing or modifying the actual global and local namespaces.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Alternatives and Safe Usage Scenarios<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">There are safer alternatives for certain use cases of <code>exec<\/code> and <code>eval<\/code>. For example, if you&#8217;re evaluating mathematical expressions, consider using <code>ast.literal_eval()<\/code>, which only evaluates literals and is therefore much safer:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import<\/span> ast\n\nexpression = <span class=\"hljs-string\">\"&#91;1, 2, 3] + &#91;4, 5, 6]\"<\/span>\nresult = ast.literal_eval(expression)\nprint(result)  <span class=\"hljs-comment\"># Outputs: &#91;1, 2, 3, 4, 5, 6]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">For more complex use cases, you might want to consider creating custom parsers or utilizing libraries designed for that purpose.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In scenarios where <code>exec<\/code> and <code>eval<\/code> are necessary, you can use them more safely by minimizing their scope:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Safer usage of exec<\/span>\ncode = <span class=\"hljs-string\">\"a = 5\"<\/span>\nglobals_ = {}\nlocals_ = {}\nexec(code, globals_, locals_)\nprint(locals_)  <span class=\"hljs-comment\"># Outputs: {'a': 5}<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, an empty dictionary is passed as <code>globals<\/code> and <code>locals<\/code> to <code>exec<\/code>, limiting the scope of the executed code. This prevents the code from accessing or modifying the actual global and local namespaces, mitigating potential risks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practical Application: Dynamic Code Generation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dynamic code generation, which involves creating and executing code on the fly during program execution, is a powerful technique that can greatly enhance the flexibility and adaptability of software. Python&#8217;s <code>exec<\/code> and <code>eval<\/code> functions enable this capability, providing an interface to execute or evaluate Python code dynamically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation of Dynamic Code Generation and Its Benefits<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Dynamic code generation refers to the creation and execution of code during runtime, as opposed to the static code which is written before a program is run. This approach can enable a software system to adapt to changes in requirements or conditions during its execution.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The benefits of dynamic code generation include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Flexibility<\/strong>: Dynamic code generation can enable a program to adapt its behavior based on runtime conditions, user input, or other factors.<\/li>\n\n\n\n<li><strong>Efficiency<\/strong>: In some cases, dynamic code generation can be used to optimize performance by generating specialized versions of functions or algorithms based on the specific data they are processing.<\/li>\n\n\n\n<li><strong>Interactivity<\/strong>: Dynamic code generation can enhance the interactivity of a program, such as by allowing users to define custom functions or calculations.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Step-by-step Guide on Creating Dynamic Code with <code>exec<\/code> and <code>eval<\/code><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s explore a practical application of dynamic code generation using <code>exec<\/code> and <code>eval<\/code> through a simple interactive calculator.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Define the Calculator Function<\/strong>: The calculator function will take an arithmetic expression as a string and evaluate it using the <code>eval<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">calculator<\/span><span class=\"hljs-params\">(expression)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> eval(expression)\n    <span class=\"hljs-keyword\">except<\/span> Exception <span class=\"hljs-keyword\">as<\/span> e:\n        print(<span class=\"hljs-string\">f\"Invalid expression: <span class=\"hljs-subst\">{e}<\/span>\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Interact with the User<\/strong>: The program interacts with the user, accepting input for arithmetic expressions and using the calculator function to evaluate them:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">while<\/span> <span class=\"hljs-literal\">True<\/span>:\n    expression = input(<span class=\"hljs-string\">\"Enter an arithmetic expression (or 'q' to quit): \"<\/span>)\n    \n    <span class=\"hljs-keyword\">if<\/span> expression.lower() == <span class=\"hljs-string\">'q'<\/span>:\n        <span class=\"hljs-keyword\">break<\/span>\n\n    result = calculator(expression)\n\n    <span class=\"hljs-keyword\">if<\/span> result <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-keyword\">not<\/span> <span class=\"hljs-literal\">None<\/span>:\n        print(<span class=\"hljs-string\">f\"Result: <span class=\"hljs-subst\">{result}<\/span>\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Practical Examples and Results Analysis<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Running the above interactive calculator program allows users to enter arithmetic expressions, which are evaluated dynamically. Here are some example inputs and outputs:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Input: <code>2 + 3 * 4<\/code><\/li>\n\n\n\n<li>Output: <code>14<\/code><\/li>\n\n\n\n<li>Input: <code>(2 + 3) * 4<\/code><\/li>\n\n\n\n<li>Output: <code>20<\/code><\/li>\n\n\n\n<li>Input: <code>2 +<\/code><\/li>\n\n\n\n<li>Output: <code>Invalid expression: invalid syntax<\/code><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The program correctly evaluates valid arithmetic expressions and provides appropriate error messages for invalid ones. This demonstrates the use of <code>eval<\/code> for dynamic code evaluation in a simple yet practical application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, remember that this calculator program should not be exposed to untrusted users or used with untrusted inputs, as it could be vulnerable to code injection attacks.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the field of programming, the power of flexibility and adaptability cannot be overstated. One such powerful concept is dynamic code generation and execution, a process that provides programs with the ability to create and execute code on-the-fly, thereby enabling unparalleled flexibility in how they operate. This technique, a prominent feature in many programming languages, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[4,6],"tags":[],"class_list":["post-85","post","type-post","status-publish","format-standard","category-programming-languages","category-python","entry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Dynamic Code Generation &amp; Execution with Python&#039;s exec and eval<\/title>\n<meta name=\"description\" content=\"Explore dynamic code generation and execution with Python&#039;s powerful exec and eval functions. Uncover use cases, performance considerations,\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Dynamic Code Generation &amp; Execution with Python&#039;s exec and eval\" \/>\n<meta property=\"og:description\" content=\"Explore dynamic code generation and execution with Python&#039;s powerful exec and eval functions. Uncover use cases, performance considerations,\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-04-02T01:29:25+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-08-23T16:22:34+00:00\" \/>\n<meta name=\"author\" content=\"w3compadmin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"w3compadmin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"TechArticle\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/\"},\"author\":{\"name\":\"w3compadmin\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"headline\":\"Dynamic Code Generation &#038; Execution with Python&#8217;s exec and eval\",\"datePublished\":\"2023-04-02T01:29:25+00:00\",\"dateModified\":\"2023-08-23T16:22:34+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/\"},\"wordCount\":1995,\"commentCount\":0,\"articleSection\":[\"Programming Languages\",\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/\",\"name\":\"Dynamic Code Generation & Execution with Python's exec and eval\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\"},\"datePublished\":\"2023-04-02T01:29:25+00:00\",\"dateModified\":\"2023-08-23T16:22:34+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"description\":\"Explore dynamic code generation and execution with Python's powerful exec and eval functions. Uncover use cases, performance considerations,\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/dynamic-code-generation-execution-pythons-exec-eval\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Articles Home\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Programming Languages\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/programming-languages\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Dynamic Code Generation &#038; Execution with Python&#8217;s exec and eval\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\",\"name\":\"Developer Articles Hub\",\"description\":\"\",\"alternateName\":\"Developer Articles\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\",\"name\":\"w3compadmin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1781352167\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1781352167\",\"contentUrl\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1781352167\",\"caption\":\"w3compadmin\"},\"sameAs\":[\"http:\\\/\\\/w3computing.com\\\/articles\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Dynamic Code Generation & Execution with Python's exec and eval","description":"Explore dynamic code generation and execution with Python's powerful exec and eval functions. Uncover use cases, performance considerations,","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/","og_locale":"en_US","og_type":"article","og_title":"Dynamic Code Generation & Execution with Python's exec and eval","og_description":"Explore dynamic code generation and execution with Python's powerful exec and eval functions. Uncover use cases, performance considerations,","og_url":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/","article_published_time":"2023-04-02T01:29:25+00:00","article_modified_time":"2023-08-23T16:22:34+00:00","author":"w3compadmin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"w3compadmin","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"TechArticle","@id":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/#article","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/"},"author":{"name":"w3compadmin","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"headline":"Dynamic Code Generation &#038; Execution with Python&#8217;s exec and eval","datePublished":"2023-04-02T01:29:25+00:00","dateModified":"2023-08-23T16:22:34+00:00","mainEntityOfPage":{"@id":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/"},"wordCount":1995,"commentCount":0,"articleSection":["Programming Languages","Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/","url":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/","name":"Dynamic Code Generation & Execution with Python's exec and eval","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/#website"},"datePublished":"2023-04-02T01:29:25+00:00","dateModified":"2023-08-23T16:22:34+00:00","author":{"@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"description":"Explore dynamic code generation and execution with Python's powerful exec and eval functions. Uncover use cases, performance considerations,","breadcrumb":{"@id":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.w3computing.com\/articles\/dynamic-code-generation-execution-pythons-exec-eval\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Articles Home","item":"https:\/\/www.w3computing.com\/articles\/"},{"@type":"ListItem","position":2,"name":"Programming Languages","item":"https:\/\/www.w3computing.com\/articles\/programming-languages\/"},{"@type":"ListItem","position":3,"name":"Dynamic Code Generation &#038; Execution with Python&#8217;s exec and eval"}]},{"@type":"WebSite","@id":"https:\/\/www.w3computing.com\/articles\/#website","url":"https:\/\/www.w3computing.com\/articles\/","name":"Developer Articles Hub","description":"","alternateName":"Developer Articles","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.w3computing.com\/articles\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561","name":"w3compadmin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1781352167","url":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1781352167","contentUrl":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1781352167","caption":"w3compadmin"},"sameAs":["http:\/\/w3computing.com\/articles"]}]}},"featured_image_src":null,"featured_image_src_square":null,"author_info":{"display_name":"w3compadmin","author_link":"https:\/\/www.w3computing.com\/articles\/author\/w3compadmin\/"},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/85","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/comments?post=85"}],"version-history":[{"count":14,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/85\/revisions"}],"predecessor-version":[{"id":746,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/85\/revisions\/746"}],"wp:attachment":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/media?parent=85"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/categories?post=85"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/tags?post=85"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}