Keyword arguments - strange behaviour?

Steven Bethard steven.bethard at gmail.com
Tue Dec 21 13:59:05 EST 2004


brian.bird at securetrading.com wrote:
> However, is there a good reason why default parameters aren't evaluated
> as the function is called? (apart from efficiency and backwards
> compatibility)?

So, one of my really common use cases that takes advantage of the fact 
that default parameters are evaluated at function definition time:

def foo(bar, baz, matcher=re.compile(r'...')):
     ...
     text = matcher.sub(r'...', text)
     ...

If default parameters were evaluated when the function was called, my 
regular expression would get re-compiled every time foo() was called. 
This would be inefficient, especially if foo() got called a lot.  If 
Python 3000 changed the evaluation time of default parameters, I could 
rewrite this code as:

class foo(object):
     matcher=re.compile(r'...')
     def __new__(self, bar, baz, matcher=None):
         if matcher is None:
             matcher = self.matcher
         ...
         text = matcher.sub(r'...', text)
         ...

But that seems like a lot of work to do something that used to be pretty 
simple...

Steve



More information about the Python-list mailing list