Scope Problem

Peter Otten __peter__ at web.de
Thu Aug 5 14:45:27 CEST 2004


Nickolay Kolev wrote:

Python doesn't support tail recursion; your algorithm is not only
inefficient but incorrect. The number of allowed recursion levels is
significantly below the maximum number of list entries.

>>> import sys
>>> sys.setrecursionlimit(10) # reduced for demonstration purposes
>>> def index(seq, value, n=0):
...     try:
...             if seq[n] == value:
...                     return n
...             else:
...                     return index(seq, value, n+1)
...     except IndexError:
...             return -1
...
>>> index(range(5), "a")
-1
>>> index(range(10), "a")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in index
  File "<stdin>", line 6, in index
  File "<stdin>", line 6, in index
  File "<stdin>", line 6, in index
  File "<stdin>", line 6, in index
  File "<stdin>", line 6, in index
  File "<stdin>", line 6, in index
  File "<stdin>", line 6, in index
  File "<stdin>", line 6, in index
RuntimeError: maximum recursion depth exceeded

The

def f(value=None):
    if value is None:
        # set real default

idiom is only needed for mutable default values.

> @Irmen
> @Daniel

I see finally someone is embracing the decorator style slated for 2.4 :-)

Peter




More information about the Python-list mailing list