Good uses for mutable function argument default values?
You can use it to cache values between function calls:
def get_from_cache(name, cache={}): if name in cache: return cache[name] cache[name] = result = expensive_calculation() return result
but usually that sort of thing is done better with a class as you can then have additional attributes to clear the cache etc.
Canonical answer is this page: http://effbot.org/zone/default-values.htm
It also mentions 3 "good" use cases for mutable default argument:
- binding local variable to current value of outer variable in a callback
- cache/memoization
- local rebinding of global names (for highly optimized code)
Maybe you do not mutate the mutable argument, but do expect a mutable argument:
def foo(x, y, config={}): my_config = {'debug': True, 'verbose': False} my_config.update(config) return bar(x, my_config) + baz(y, my_config)
(Yes, I know you can use config=()
in this particular case, but I find that less clear and less general.)