2

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
3
  • Can you think of anything that can be referenced in such a way once it has been deleted? Commented Nov 8, 2019 at 20:39
  • @ScottHunter Yes, I can. Hence the question. Commented Nov 8, 2019 at 20:56
  • Care to share what that might be? Commented Nov 9, 2019 at 1:34

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

It's not exactly an answer to my question - so I assume the answer is 'no' - , but still the best workaround I can think of. Therefore: accepted. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.