1

I have this:

>>> d = {}
>>> d["hi"] = 12345

>>> d1 = {}

>>> d1["hiiii"] = 1234590

I know why I get an error below. This is because exec could not find variables hi and hiiii.

>>> exec "print hi, hiiii"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hi' is not defined


>>> exec "print hiiii"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hiiii' is not defined

Now it works because exec was able to find hi and hiiii variables in dictionary d and d1

>>> exec "print hi, hiiii" in d , d1
12345 1234590

So far so good.

Question:

Now when I print d I see that it has been modified and prints lot of key,value pairs..why? But on printing d1 I do not see lot of key,value pairs, why so?

1 Answer 1

3

This is explained in the docs:

As a side effect, an implementation may insert additional keys into the dictionaries given besides those corresponding to variable names set by the executed code. For example, the current implementation may add a reference to the dictionary of the built-in module __builtin__ under the key __builtins__ (!).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.