[issue7286] odd exec() behavior or documentation

Peter Mawhorter report at bugs.python.org
Sun Nov 8 07:39:06 CET 2009

New submission from Peter Mawhorter <pmawhorter at gmail.com>:

The behavior of the built-in exec() function differs in Python3.1 from
the behavior in Python 2.6 when only a single argument is passed.
Additionally, the documentation for the function does not suggest the
behavior that it has. In Python2.6, an exec statement could both access
and change the values of local variables. In Python3.1, it can read
values from the local scope, but can't change them. Run the attached
script to see examples of this behavior. Note especially that in the
first function, the exec'd code changes the value of a variable called
'value'. However, the change isn't visible after the call to exec(),
because the value changed was a local variable and presumably, the
update is dropped after the exec() finishes. To me, this conflicts with
the statement in the documentation that "In all cases, if the optional
parts are omitted, the code is executed in the current scope." At the
very least, a sentence or two should be added to the documentation
explaining that exec() can't affect the value of local variables. In
addition, it's strange that, for example, in a function declaring
"global value", an exec() statement that modifies 'value' doesn't affect
the value of the global variable. In this sense, the code being exec'd
doesn't seem to be running in a perfect copy of the function's scope.

If it were up to me, I'd allow code being executed by an exec()
statement to modify the value of local variables, because that keeps
with the paradigm of the exec'd code being simply dynamic code that
behaves as if it were written in-line. It also means that programmers
who need to change things with an exec statement aren't limited to
pushing their changes through global variables, which can lead to
conflicts with name sharing (for example, what if my exec() statement is
in a recursive function?). Of course, implementing this may be
difficult... so it may be better just to add to the documentation to
explain this behavior of exec().

assignee: georg.brandl
components: Documentation, Interpreter Core
files: test.py
messages: 95036
nosy: georg.brandl, pmawhorter
severity: normal
status: open
title: odd exec() behavior or documentation
type: behavior
versions: Python 3.1
Added file: http://bugs.python.org/file15289/test.py

Python tracker <report at bugs.python.org>

More information about the Python-bugs-list mailing list