Emmanuel Mtali
Emmanuel Mtali

Reputation: 4963

Why global and local namespaces are always the same in interactive session

Running locals() and globals() inside IDLE returns the same keys/values

I am extracting keys only with .keys() and convert to list using list()

['__doc__', '__spec__', '__builtins__', '__loader__', '__name__', '__package__']

Running the following code

z = 100
def f(x):
    y = 100
    return y
f(z)

Checking locals and globals again, all have the same keys/values

['z', '__doc__', '__spec__', '__builtins__', '__loader__', '__name__', '__package__', 'f']

Why this is happening and why is variable y and x not showing up

Upvotes: 0

Views: 36

Answers (1)

bli
bli

Reputation: 8184

The variables that are defined inside the function do not exist any more after the function returned.

This is what allows you to have several functions with same internal variable names without interferences.

If you call locals() after the function call, x and y will therefore not appear.

Upvotes: 1

Related Questions