Keyword arguments - strange behaviour?

Fuzzyman fuzzyman at gmail.com
Thu Dec 23 06:48:59 EST 2004


Steven Bethard wrote:
> 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)
>      ...
>

Surely "re.compile(r'...')" is effectively a constant ? So your above
code is equivalent to :

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

I agree that dynamic evaluation of default arguments seems much more
pythonic, as well as getting rid of a common python gotcha.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shmtl

> 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