Function Details: exec

Description


Executes Python code dynamically.


Extended Description


The exec() function is used to dynamically execute Python code. It can execute a string containing Python code, a code object, or a file. The globals and locals parameters can be used to specify the environment in which the code is executed. Unlike eval(), exec() can execute statements that don't return a value. It's important to use exec() cautiously, especially with untrusted input, as it can execute arbitrary Python code.


Exceptions


  • SyntaxError: If the string contains invalid Python syntax
  • NameError: If a name used in the code is not defined
  • TypeError: If an operation in the code is applied to an object of inappropriate type

Read More about exec from Python Documentation

Function Signature


exec(object: Union[str, code], globals: Optional[dict] = None, locals: Optional[dict] = None) -> None

Module: builtins

Parameters


object: A string, bytes or code object containing Python code to be executed. globals: Optional dictionary to specify global variables available to the code being executed. locals: Optional dictionary to specify local variables available to the code being executed.


Parameter List


  • object: Union[str, code]
  • globals: Optional[dict]
  • locals: Optional[dict]

Return


This function doesn't return a value; it executes the given code in place.


Return Type


None

Output

Explanation

This example shows basic usage of exec() to execute a print statement and modify a variable.