side effects on *some* default parameters
Duncan Booth
duncan at NOSPAMrcp.co.uk
Fri Feb 14 05:18:46 EST 2003
Joe Grossberg <jgrossberg at matrixgroup.net> wrote in
news:mailman.1045154045.19349.python-list at python.org:
> *Why* is this better than the alternative (i.e. default argument
> values get created every time the method/function is called without
> the parameter)?
>
Code like the following depends on the fact that the default argument
values are only evaluated once when 'def' is executed, rather than when the
function is called:
>>> adders = []
>>> for i in range(10):
def addN(x, n=i): return x+n
adders.append(addN)
>>> adders[4](3)
7
If the default argument was evaluated when the function was called, this
would display 12 instead of 7. There would be no easy way to replicate the
current behaviour if this were the case.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list