Tail recursion to while iteration in 2 easy steps

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Oct 4 06:51:08 EDT 2013


On Fri, 04 Oct 2013 11:49:26 +0200, Alain Ketterlin wrote:

> I think allowing rebinding of function names is extremely strange,

It's not, it's quite common. Functions in Python are first-class values, 
and we can do things like this:

from somelibrary import somethingwithalonglongname as shortname

def inorder(tree, op=print):
    # Walk the tree in infix order, doing op to each node.
    process(tree.left, op)
    op(tree.payload)
    process(tree.right, op)

_len = len
def len(obj):
    do_something_first()
    return _len(obj)


Now, the first two aren't the same sort of function-rebinding that you're 
talking about, or that were shown in your post, but the third is. What is 
unusual though is rebinding a function from within itself:

def func(arg):
    global func
    do_this(arg)
    def func(arg):
        do_that(arg)


but it's legal and it sometimes can be useful, although it counts as 
"clever code", possibly "too clever".



-- 
Steven



More information about the Python-list mailing list