Explaining exec(globals, separate_locals)

Terry Reedy tjreedy at udel.edu
Mon Sep 20 12:46:24 EDT 2021


The second paragraph of the current exec entry
https://docs.python.org/3.11/library/functions.html#exec
ends with a sentence I wrote.

"If exec gets two separate objects as globals and locals, the code will 
be executed as if it were embedded in a class definition."

Would the following would be clearer?

"If exec gets two separate objects as globals and locals, the code will 
be executed in two namespaces, the same as is done with the suite of a 
class statements."

In either case, does the following help even more?

"(The difference is that the locals for exec is not passed to type() to 
become a class dict.)"

I am asking because the current sentence engenders questions.  Today I 
got a private email with "This behavior seems really peculiar to me, and 
I would love to know if you know about why this behavior was chosen to 
be as it is."

The answer is that the choice is made by the user by what the user 
passes.  Top level code is executed in one namespace serving as both 
globals and locals.  Class definition code is executed in two separate 
namespaces serving the two role.  The populated local namespace is then 
passed to type() to become the __dict__ of the resulting class.  An 
interpreter written in Python could use exec for the two cases.  IDLE, 
for instance, uses exec, with *one* namespace, to execute user code as 
toplevel code.

The third type of code is function code, which executes in 2 *or more* 
namespaces, with peculiar locals behavior, and with 'return', 'yield', 
and 'nonlocal' valid.  It would make no sense to treat the code passed 
to exec as a function suite.

-- 
Terry Jan Reedy



More information about the Python-list mailing list