renaming 'references' to functions can give recursive problems
Satchidanand Haridas
sharidas at zeomega.com
Wed Feb 16 12:42:02 EST 2005
peter wrote:
>Hello, nice solution:
>but it puzzles me :)
>
>can anyone tell me why
>-----------correct solution----------------
>def fA(input):
> return input
>
>def newFA(input, f= fA):
> return f(input)
>
>fA = newFA
>
>is correct and:
>
>
>>> def fA(input):
... print "inside fA"
... return input
...
>>> def newFA(input,f=fA):
... print "inside newFA"
... return f(input)
...
>>> fA = newFA
>>> fA(2)
inside newFA
inside fA
2
while:
>-------------infinite loop-----------------
>
>def fA(input):
> return input
>
>def newFA(input):
> return fA(input)
>
>fA = newFA
>
>gives an infinite recursive loop?
>
>
>
>>> def fA(input):
... print "inside fA"
... return input
...
>>> def newFA(input):
... print "inside newFA"
... return fA(input)
...
>>> fA = newFA
>>> fA(2)
inside newFA
inside newFA
inside newFA
inside newFA
What is happening is that when you call fA (inside newFA) in the second
case, you are calling newFA because fA is pointing to newFA (hope that
made sense ;-)). So it was recursive. While in the former case you
called f, which pointed to fA, but not to newFA. Probably the following
will make it clearer:
>>> def fA(input):
... print "inside fA"
... return input
...
>>> def newFA(input,f=fA):
... print "inside newFA"
... print "f is pointing to: ",f
... return f(input)
...
>>> fA = newFA
>>> fA(2)
inside newFA
f is pointing to: <function fA at 0x43123374>
inside fA
2
>>> fA
<function newFA at 0x43194064>
>>> newFA
<function newFA at 0x43194064>
Thus f and fA do not point to the same function object when you execute
the statement fa(2). This f is called once and terminates.
thanks,
Satchit
More information about the Python-list
mailing list