Recursive functions (was Re: Observations on the three pillars of Python execution)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 5 10:44:20 EDT 2011


Chris Angelico wrote:

> On Fri, Aug 5, 2011 at 9:22 AM, Thomas Jollans <t at jollybox.de> wrote:
>> On 05/08/11 09:20, Eric Snow wrote:
>>> Object available during code object execution:
>>> (M) no
>>> (C) no
>>> (F) no
>> (F) yes.
>>
>> cf. recursion.
> 
> Is it? As I understand it, a Python function is not able to reference
> "itself" but must reference its own name.

That is correct. Recursion in Python is implemented simply by name lookup.


> This means that assigning 
> that function to something else stops it being recursive:

An easier way to demonstrate the process:

>>> def f(x):
...     print x
...     if x > 0: f(x-1)
...
>>> f(3)
3
2
1
0
>>> g = f
>>> del f
>>> g(3)
3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in f
NameError: global name 'f' is not defined


-- 
Steven




More information about the Python-list mailing list