Mutable defaults

Ross Wilson rzzzwilson at gmail.com
Thu Feb 11 02:02:21 EST 2021


On Thu, 11 Feb 2564 BE at 12:52 Grant Edwards <grant.b.edwards at gmail.com>
wrote:

> On 2021-02-11, J. Pic <jpic at yourlabs.org> wrote:
>
> > I just meant removing the whole "default value mutating" story, not
> > removing mutable variables. Really, I was wondering if there was a use
> case
> > where this actually turns to an advantage,
>
> I've seen people show how it can be used to provide function-scope
> persistent storage -- the equivalent of declaring a static variable in
> a C function. I don't think I've seen that done in the wild, though.


Not sure this qualifies as "use in the wild", but the memoized naive
Fibonacci is very nice when written this way:

def fib(n, memo={0: 0, 1: 1}):
    if n not in memo:
        memo[n] = fib(n-1) + fib(n-2)
    return memo[n]


More information about the Python-list mailing list