Min-Soo Pipefeet
Min-Soo Pipefeet

Reputation: 2578

Recursive calls without using function's name

As you can see in the code below, recursive calls using function's name fail if the original function is deleted.

Is there any means to reference the function in its own body by something like this or self?

>>> def count_down(cur_count):
...     print(cur_count)
...     cur_count -= 1
...     if cur_count > 0:
...         count_down(cur_count)
...     else:
...         print('Ignition!')
...     
>>> count_down(3)
3
2
1
Ignition!
>>> zaehle_runter = count_down
>>> zaehle_runter(2)
2
1
Ignition!
>>> del count_down
>>> zaehle_runter(2)
2
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in count_down
NameError: name 'count_down' is not defined

Upvotes: 2

Views: 665

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

When you call your function recursively, the function name is searched in the (global) scope.

Since the name is now deleted, it cannot be found.

To workaround this, you can create an internal function that does the recursive job. That makes your recursive function not affected by this deletion, since it's no longer recursive, but just calls an internal recursive function

def count_down(cur_count):
    def internal_count_down(cur_count):
       cur_count -= 1
       if cur_count > 0:
           internal_count_down(cur_count)
       else:
           print('Ignition!')
    internal_count_down(cur_count)

Upvotes: 3

Related Questions