[Python-ideas] fixing mutable default argument values

Joel Bender jjb5 at cornell.edu
Wed May 2 19:55:07 CEST 2007


George Sakkis wrote:

>> Sure they have, and they've solved it (under different names) in
>> plenty of other languages.  In python, the only current solution seems
>> to be turning the function into a class (with self) or at least a
>> closure.  People have griped about this.
> 
> User-defined function attributes is another handy solution.
> 
>> For What Its Worth, my personal opinion is that having to create an
>> object instead of a function is annoying, but not so bad (or so
>> frequent) that it is worth special syntax.
> 
> Function attributes fit the bill really good if writing a class is too
> much overhead.

To follow up on this, here is a way to get something pretty close to 
what I wanted.  From this...

     def foo(x):
         local history = []
         history.append(x)

To this...

     def local(**locals):
         def _local(fn):
             fn.__dict__.update(locals)
             return fn
         return _local

     @local(history = [])
     def foo(x):
         foo.history.append(x)

I like this because it keeps history out of the parameter list, and 
while it's not part of the local namespace, it's readily accessible.


Joel



More information about the Python-ideas mailing list