Proper tail recursion

Duncan Booth me at privacy.net
Tue Jul 6 09:47:52 EDT 2004


Christopher T King <squirrel at WPI.EDU> wrote in 
news:Pine.LNX.4.44.0407060839230.18699-100000 at ccc4.wpi.edu:

> Is it feasable, and/or desirable to have Python optimize tail-recursive 
> calls, similar to Scheme and gcc -O2? i.e. effectively compile this:
> 
> def foo(n):
>     return foo(n-1)
> 
> into this:
> 
> def foo(n):
>     goto foo(n-1)
> 
> This would naturally only be enabled in optimized bytecode.
> 
> On an unrelated, Scheme-ish note, is there any way for a generator to 
> access itself? i.e. I want to be able to write this:
> 
> def gen():
>     yield get_current_continuation(),someothergenerator()
> 
> Thanks,
> Chris
> 
> 

Just because a function looks recursive to you, doesn't mean it actually is 
recursive when it gets called.

How do you propose to handle this?

def foo(n):
    return foo(n-1)

def baz(n):
    return 0

bar = foo
foo = baz
bar(3)

One solution might be to provide a keyword which refers to the currently 
executing function: this would be useful not only for recursion but also to 
access attributes on the function. These help with methods and generators 
which as you noted find it hard to reference themselves.

However, I don't believe there is at present any easy way to get hold of 
the current executing function or generator object.



More information about the Python-list mailing list