Code Explanation:
๐น 1. Creating an Empty Dictionary
namespace = {}
✅ Explanation
An empty dictionary named namespace is created.
This dictionary will act as a custom memory space for the exec() function.
Instead of creating variables in the current program, exec() will store them inside this dictionary.
Current Memory
namespace
↓
{}
Think of it as creating an empty room where Python can store variables.
๐น 2. Calling exec()
exec(
"x = 100\ny = 50",
namespace
)
✅ Explanation
exec() executes Python code that is stored as a string.
Syntax:
exec(source_code, globals_dictionary)
Here,
Source Code →
"x = 100\ny = 50"
Global Namespace →
namespace
Python does not create variables in the current program.
Instead, it stores them inside the namespace dictionary.
๐น 3. Understanding the Code String
"x = 100\ny = 50"
✅ Explanation
This string contains two Python statements.
The special character:
\n
means new line.
So Python actually sees:
x = 100
y = 50
Execution order:
Line 1
x = 100
↓
Line 2
y = 50
๐น 4. Executing the First Statement
x = 100
✅ Explanation
Normally, Python would create:
x
↓
100
But because a custom namespace is supplied, Python stores it as:
namespace
↓
{
"x":100
}
Current dictionary:
{
"x":100
}
๐น 5. Executing the Second Statement
y = 50
✅ Explanation
Python now creates another variable inside the same dictionary.
Current dictionary becomes:
{
"x":100,
"y":50
}
Notice that both variables are stored inside namespace, not as normal global variables.
๐น 6. Final State of the Namespace
After exec() finishes, the dictionary contains the created variables.
Current memory:
namespace
↓
{
"x":100,
"y":50
}
(Python also automatically adds a special key named __builtins__ internally, but it is omitted here for simplicity.)
๐น 7. Accessing "x"
print(namespace["x"])
✅ Explanation
Python searches for the key:
"x"
inside the dictionary.
Current dictionary:
{
"x":100,
"y":50
}
Value found:
100
Python prints:
100
๐น 8. Accessing "y"
print(namespace["y"])
✅ Explanation
Python searches for:
"y"
Current dictionary:
{
"x":100,
"y":50
}
Value found:
50
Python prints:
50
๐ฏ Final Output
100
50

0 Comments:
Post a Comment