This recipe provides a decorator for keeping mutable default function values fresh between calls.
Python, 18 lines
In Python, a function's default values are evaluated once, and only once, at definition time. Beginning Python programmers are often caught out by this distinction when they try to use mutable default values, e.g., lists, dicts, etc. 
The recommended practice is to not use mutable default values. Instead, you should use the following idiom:
<pre> def packitem(item, pkg=None): if pkg is None: pkg =  pkg.append(item) return pkg </pre>
The freshdefaults() decorator provides another way to accomplish the same task. It removes the need to declare your default value with something other than the value you intend it to have (None rather than ). It also removes the need to test against the stand-in value before assigning the intended value (which could be of benefit, were you to need several mutable default arguments).
At the same time, however, it adds a layer of indirection to the code and it introduces concepts (decorators, closures, function attributes, deep copying) that will likely be more difficult to explain to beginning Python programmers than is the recommended idiom.