Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Do recursive functions in Python create a new namespace each time the function calls itself?
Yes, recursive functions in Python create a new namespace each time the function calls itself. This is true for any function call, not just recursive ones. However, when objects are passed as parameters, they are passed by reference.
The new namespace gets its own copy of this reference, but it still refers to the same object as in the calling function. If you modify the content of that object, the change will be visible in the calling function.
How Python Handles Function Calls
When the Python interpreter encounters a function call, it creates a frame object that gets pushed onto the frame stack. Each frame has its own private namespace where variables are defined locally to that function call.
Example: Recursive Function with New Namespaces
Let's see how each recursive call creates its own namespace ?
def countdown(n):
print(f"Local variable n = {n}, id = {id(n)}")
if n > 0:
countdown(n - 1)
print(f"Returning from n = {n}")
countdown(3)
Local variable n = 3, id = 140712345678976 Local variable n = 2, id = 140712345678944 Local variable n = 1, id = 140712345678912 Local variable n = 0, id = 140712345678880 Returning from n = 0 Returning from n = 1 Returning from n = 2 Returning from n = 3
Example: Object References Across Recursive Calls
When passing mutable objects, all recursive calls share the same object reference ?
def append_numbers(numbers, n):
print(f"Call with n={n}, list id: {id(numbers)}")
print(f"Current list: {numbers}")
if n > 0:
numbers.append(n)
append_numbers(numbers, n - 1)
my_list = []
print(f"Original list id: {id(my_list)}")
append_numbers(my_list, 3)
print(f"Final list: {my_list}")
Original list id: 140712346789120 Call with n=3, list id: 140712346789120 Current list: [] Call with n=2, list id: 140712346789120 Current list: [3] Call with n=1, list id: 140712346789120 Current list: [3, 2] Call with n=0, list id: 140712346789120 Current list: [3, 2, 1] Final list: [3, 2, 1]
Key Points
| Aspect | Behavior | Example |
|---|---|---|
| Local Variables | New copy in each namespace | Each n parameter is independent |
| Mutable Objects | Same reference shared | List modifications visible across calls |
| Frame Stack | New frame per call | Each call has its own execution context |
Conclusion
Each recursive call creates a new namespace with its own local variables. However, mutable objects passed as parameters share the same reference across all recursive calls, making modifications visible throughout the call stack.
---