Keyword arguments - strange behaviour?

Fuzzyman fuzzyman at gmail.com
Thu Dec 23 16:44:46 CET 2004


Steven Bethard wrote:
> Fuzzyman wrote:
> > 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)
> > ...
>
> Basically, yes.  Though you add an extra name to the module or class
> namespace by defining 'aConst'.  I consider this a minor pollution of

> the namespace since 'matcher' is only used in the function, not the
> module or class.
>
> But if we're arguing for equivalencies, the oft-asked for
>
> def foo(lst=[]):
>      ...
>
> where [] is evaluated for each function call, is equivalent for most
> purposes to:
>
> def foo(lst=None):
>      if lst is None:
>          lst = []
>
> There's a minor pollution of the range of values 'lst' can take on --
if
> you need lst to be able to take on the value None, you'll want to
> rewrite this something like:
>
> no_value = object()
> def foo(lst=no_value):
>      if lst is no_value:
>          lst = []
>
> My point here is that there's always going to be some equivalent
> expression (turing completeness etc.)  I was just pointing out a
quite
> reasonable use of the current default parameter evaluation system.
>
> Steve

Sure.. but you also gave an example of an alternative that was complex,
and used it's complexity as an argument against having default
arguments dynamically evaluated. What I was saying is that there is an
alternative that is at least as readable (if not more) than your
example.

Having default arguments evaluated when the function is defined is
unintuitive and unpythonic.
Regards,


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




More information about the Python-list mailing list