Enclosing Namespace Python

There is just one more namespace we need to be aware of in our Python programs. This particular namespace is a special type of local namespace called the enclosing namespace.

Enclosing namespaces are created specifically when we work with nested functions and just like with the local namespace, will only exist until the function is done executing. Let’s take a look at an example:

global_variable = 'global' def outer_function(): outer_value = "outer" def inner_function(): inner_value = "inner" inner_function() outer_function()

In this program, the following occurs:

  • We define a function called outer_function() and nest another function inside it called inner_function(). To generate a namespace, functions must be executed, so we are calling both of them.
  • Here, The outer_function() serves the role of an enclosing function while inner_function is an enclosed function. By creating this structure, we generate an enclosing namespace - a namespace created by an enclosing function and any number of enclosed functions inside it.

While Python doesn’t give us any particular function like enclosing() to visualize the namespace, we can use locals() to see when enclosed namespaces are generated. Let’s take a look by modifying our script:

global_variable = 'global' def outer_function(): outer_value = "outer" def inner_function(): inner_value = "inner" inner_function() # Added locals output print(locals()) outer_function()

Would output:

{'outer_value': 'outer', 'inner_function': <function outer_function.<locals>.inner_function at 0x7f46b56bc820>}

Notice the 'inner_function': <function outer_function.<locals>.inner_function shows that our local namespace inside of outer_function() encloses the local namespace of inner_function().

Let’s practice accessing the enclosing namespace in a similar example!



Examine the nested functions in the code editor. Let’s try to examine the enclosing namespace.

At the line that says # Add locals() call below: print the locals() function.

Spot anything significant?

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?