Bug in python!? persistent value of an optional parameter in function!
Steven D'Aprano
steve at REMOVEME.cybersource.com.au
Wed Mar 7 23:07:52 EST 2007
On Thu, 08 Mar 2007 03:14:53 +0000, John Nagle wrote:
> Paul Rubin wrote:
>> "C Barr Leigh" <cpblPublic at gmail.com> writes:
>>
>>>Help! Have I found a serious bug?
>>>This seems like highly undesired behaviour to me. From the program
>>>below, I get output:
>>
>>
>> It is intentional, not a bug, see the docs. Whether it's desirable is
>> a different question.
>
> True. It would make sense to disallow mutable values as
> initial values for optional arguments. The present behavior
> is silly.
It's just *different*, not silly.
It's also quite useful in some circumstances, e.g. cheap caching without
using a global variable.
def factorial(n, _cache={}):
try:
return _cache[n]
except KeyError:
# fall back to slow calculation
if n <= 1:
result = 1
else:
result = factorial(n-1)*n
_cache[n] = result
return result
There are other ways of implementing caches, but this is quick and easy
and works well for many functions.
--
Steven D'Aprano
More information about the Python-list
mailing list