Keyword arguments - strange behaviour?
Steven Bethard
steven.bethard at gmail.com
Thu Dec 23 10:35:45 EST 2004
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
More information about the Python-list
mailing list