Fundamentals 13 min read

Understanding Python eval(), exec(), compile(), globals() and locals() Functions

This article explains the purpose, usage, parameters, return values, and differences of Python's eval, exec, compile, globals, and locals functions, providing detailed code examples and output analysis to help readers grasp how these built‑ins work in various execution contexts.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Python eval(), exec(), compile(), globals() and locals() Functions

The article introduces Python's built‑in functions eval() , exec() , compile() , globals() and locals() , emphasizing their importance for a deeper understanding of the language.

1. eval Function

Purpose: Calculates the value of a given expression. It can only evaluate a single expression, not arbitrary statements, similar to a lambda.

Definition:

<code>eval(expression, globals=None, locals=None)</code>

Parameters:

expression : required; a string or a code object created by compile() . If a string, it is evaluated using the provided globals and locals namespaces.

globals : optional dictionary representing the global namespace.

locals : optional mapping representing the local namespace; defaults to the same object as globals when omitted.

Return value:

If expression is a code object compiled with mode 'exec' , eval() returns None .

If the expression produces output (e.g., print() ), the return value is None .

Otherwise, the result of the evaluated expression is returned.

Example:

<code>x = 10

def func():
    y = 20
    a = eval('x + y')
    print('a: ', a)
    b = eval('x + y', {'x': 1, 'y': 2})
    print('b: ', b)
    c = eval('x + y', {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
    print('c: ', c)
    d = eval('print(x, y)')
    print('d: ', d)

func()
</code>

Output:

<code>a:  30
b:  3
c:  4
10 20
d:  None
</code>

Explanation of the results highlights how globals and locals affect variable resolution.

2. exec Function

Purpose: Dynamically executes Python code, allowing complex statements and multiple lines, unlike eval() which is limited to single expressions.

Definition:

<code>exec(object[, globals[, locals]])</code>

Parameters:

object : required; a string or code object containing Python statements.

globals and locals : optional, same meaning as in eval() .

Return value: Always None .

Difference from eval: exec() can run full code blocks and never returns a value, while eval() evaluates a single expression and may return its result.

Example 1 (replacing eval with exec):

<code>x = 10

def func():
    y = 20
    a = exec('x + y')
    print('a: ', a)
    b = exec('x + y', {'x': 1, 'y': 2})
    print('b: ', b)
    c = exec('x + y', {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
    print('c: ', c)
    d = exec('print(x, y)')
    print('d: ', d)

func()
</code>

Output:

<code>a:  None
b:  None
c:  None
10 20
d:  None
</code>

All return values are None , confirming exec() 's behavior.

Example 2 (using exec with a multi‑line string):

<code>x = 10
expr = """
for x in range(10):
    print(x, end='')
print()
"""
exec(expr)
</code>

Output:

<code>0123456789
</code>

3. globals() and locals() Functions

globals(): Returns a dictionary representing the current global symbol table (the module's namespace).

locals(): Returns a dictionary representing the current local symbol table. Inside a function it contains local variables; at module level it is the same as globals() .

Both functions should not be used to modify the returned dictionaries, as changes may not affect the interpreter's actual variables.

Example:

<code>name = 'Tom'
age = 18

def func(x, y):
    sum = x + y
    _G = globals()
    _L = locals()
    print(id(_G), type(_G), _G)
    print(id(_L), type(_L), _L)

func(10, 20)
</code>

Output shows that _G contains the module‑level symbols, while _L contains only the function’s local variables.

4. compile Function

Purpose: Compiles source code into a code object (or AST) that can be executed with exec() or evaluated with eval() .

Definition:

<code>compile(source, filename, mode[, flags[, dont_inherit]])</code>

Parameters:

source : string or AST to compile.

filename : name of the file (or a placeholder) for error messages.

mode : 'exec' for statements, 'eval' for a single expression, 'single' for interactive statements.

Example:

<code>s = """
for x in range(10):
    print(x, end='')
print()
"""
code_exec = compile(s, '<string>', 'exec')
code_eval = compile('10 + 20', '<string>', 'eval')
code_single = compile('name = input("Input Your Name: ")', '<string>', 'single')

a = exec(code_exec)
b = eval(code_eval)
c = exec(code_single)
d = eval(code_single)
print('a: ', a)
print('b: ', b)
print('c: ', c)
print('name: ', name)
print('d: ', d)
print('name; ', name)
</code>

Output demonstrates that exec() returns None , while eval() returns the evaluated result.

5. Relationship of These Functions

The results of compile() , globals() and locals() can be used as arguments for eval() and exec() . Additionally, checking the dictionary returned by globals() for a specific key allows you to determine whether a global variable has already been defined.

Original source: https://www.cnblogs.com/yyds/p/6276746.html

PythonprogrammingglobalslocalsExecevalcompile
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.