Search code examples
pythonexec

How does Python's exec function work when sending an empty dictionary in the locals parameter?


I have written the following piece of code trying to use exec() to execute the code enclosed in the string. I pass an empty dictionary, d, as the locals parameter. When I print d, the local namespaces are being created in d. Can anyone help me explain that is really happening?

c = '''x = 1 
def __init__(self,n):self.name = n 
def printD(self):print(self.name)'''

d = {}
print(d)

exec(c,globals(),d)
print(d)

Solution

  • From the documentation:

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

    In a class definition, variable assignments update the local environment, not the global environment. So the names you define are put in the dictionary d.

    If you don't pass the locals dictionary the names will be defined in the global environment.