globals and locals in python exec()

globals and locals in python exec()

In Python, globals() and locals() are two built-in functions that allow you to access the global and local symbol tables, respectively. You can use these functions in conjunction with the exec() function to execute Python code dynamically while specifying the scope in which the code should run.

Here's an overview of how globals() and locals() work with exec():

  1. globals() Function:

    • The globals() function returns a dictionary representing the global symbol table, which contains all global variables and their values.

    • When you use globals() with exec(), you make the global scope available to the code executed inside exec(). This means the code can access and modify global variables.

    global_variable = 42
    
    code = """
    global_variable += 10
    print(global_variable)
    """
    
    exec(code, globals())
    
    print(global_variable)  # Output: 52
    
  2. locals() Function:

    • The locals() function returns a dictionary representing the local symbol table of the current scope.

    • When you use locals() with exec(), you make the local scope available to the code executed inside exec(). This allows the code to access and modify local variables in the current scope.

    def my_function():
        local_variable = 10
        code = """
        local_variable += 5
        print(local_variable)
        """
        exec(code, locals())
        print(local_variable)
    
    my_function()  # Output: 15, 15
    

    Note that the changes made to the local variables inside exec() do not affect the actual function's local scope.

  3. Combining globals() and locals():

    You can combine both globals() and locals() in the same exec() call to provide access to both global and local scopes. However, be cautious when doing this, as it can make code harder to understand and maintain.

    global_var = 5
    
    def my_function():
        local_var = 10
        code = """
        global_var = 20
        local_var += 5
        print(global_var, local_var)
        """
        exec(code, globals(), locals())
        print(global_var, local_var)
    
    my_function()  # Output: 20 15, 20 10
    

    Keep in mind that changes made to variables inside exec() are reflected in the dictionaries returned by globals() and locals(), but they do not automatically update the actual variable values in the current scope.

Using exec() with globals() and locals() should be done with caution, as it can make code less predictable and harder to debug. It's generally recommended to avoid using exec() for code execution unless it's absolutely necessary, as it can introduce security risks and make the code less maintainable.

Examples

  1. Understanding globals and locals in Python exec() function

    • Description: This query aims to understand how the globals() and locals() functions are utilized within the exec() function in Python, which allows for dynamic execution of code strings.
    • Code:
      code = """
      a = 10
      print(a)
      """
      global_vars = {}
      local_vars = {}
      exec(code, global_vars, local_vars)
      
  2. Python exec() function with custom global and local variables

    • Description: Demonstrates how to use the exec() function with custom global and local variable dictionaries to control the execution environment of dynamically provided code.
    • Code:
      code = """
      a = 10
      print(a)
      """
      custom_globals = {'b': 20}
      custom_locals = {}
      exec(code, custom_globals, custom_locals)
      
  3. How to access globals and locals inside Python exec() block?

    • Description: This query seeks to understand how to access the global and local variables within the code block executed by the exec() function.
    • Code:
      code = """
      print(globals())
      print(locals())
      """
      exec(code)
      
  4. Python exec() with modified global variables

    • Description: Illustrates how to use the exec() function to execute code with modified global variables, allowing for dynamic manipulation of the global namespace.
    • Code:
      code = """
      global_var += 10
      print(global_var)
      """
      global_var = 5
      exec(code)
      
  5. Customizing globals and locals dictionaries in Python exec()

    • Description: Explains how to customize the globals() and locals() dictionaries passed to the exec() function to control the scope of variables within the executed code.
    • Code:
      code = """
      a = 10
      print(a)
      """
      custom_globals = {'a': 20}
      custom_locals = {}
      exec(code, custom_globals, custom_locals)
      
  6. Using globals and locals to control variable scope in Python exec()

    • Description: Shows how to leverage the globals() and locals() dictionaries to manage the variable scope within the code block executed by the exec() function.
    • Code:
      code = """
      a = 10
      print(a)
      """
      exec(code, globals(), locals())
      
  7. How to modify global variables with Python exec()?

    • Description: Provides insights into modifying global variables using the exec() function in Python, allowing for dynamic changes to the global namespace.
    • Code:
      code = """
      global a
      a += 10
      print(a)
      """
      a = 5
      exec(code)
      
  8. Python exec() function with predefined globals and locals

    • Description: Demonstrates how to use the exec() function with predefined global and local variables to control the execution environment of dynamically provided code.
    • Code:
      code = """
      a = 10
      print(a)
      """
      exec(code, {'a': 20}, {})
      
  9. Accessing and modifying global variables inside exec() in Python

    • Description: Discusses techniques for accessing and modifying global variables within the code block executed by the exec() function in Python.
    • Code:
      code = """
      global_var += 10
      print(global_var)
      """
      global_var = 5
      exec(code, globals())
      
  10. Controlling variable scope in Python exec() using globals and locals

    • Description: Explains how to control the variable scope within the exec() function by customizing the globals() and locals() dictionaries.
    • Code:
      code = """
      a = 10
      print(a)
      """
      custom_globals = {'a': 20}
      custom_locals = {}
      exec(code, custom_globals, custom_locals)
      

More Tags

git-svn monkeypatching pascal expert-system ag-grid-ng2 nvarchar color-space ngx-datatable javac native

More Python Questions

More Transportation Calculators

More Housing Building Calculators

More Fitness-Health Calculators

More Bio laboratory Calculators