What value should be passed to make a function use the default argument value?

Antoon Pardon apardon at forel.vub.ac.be
Wed Oct 4 14:28:00 CEST 2006


On 2006-10-04, Antoon Pardon <apardon at forel.vub.ac.be> wrote:
> On 2006-10-03, LaundroMat <Laundro at gmail.com> wrote:
>> Suppose I have this function:
>>
>> def f(var=1):
>> return var*2
>>
>> What value do I have to pass to f() if I want it to evaluate var to 1?
>> I know that f() will return 2, but what if I absolutely want to pass a
>> value to f()? "None" doesn't seem to work..
>>
>> Thanks in advance.
>>
>
> I think the only general solution for your problem would be to
> define a defaulter function. Something like the following:
>
>   Default = object()
>
>   def defaulter(f, *args):
>
>     while args:
>       if args[-1] is Default:
>         args = args[:-1]
>       else:
>         break
>     return f(*args)
>
>
> The call:
>
>   defaulter(f, arg1, arg2, Default, ..., Default)
>
> would then be equivallent to:
>
>   f(arg1, arg2)
>
> Or in your case you would call:
>
>   defaulter(f, Default)

A little update, with the functools in python 2.5 you
could turn the above into a decorator. Something like
the following (not tested):

  def defaulting(f):
    return functools.partial(defaulter, f)

You could then simply write:

  @defaulting
  def f(var=1):
    return var * 2

And for built in or library functions something like:

  from itertools import repeat
  repeat = defaulting(repeat)

-- 
Antoon Pardon



More information about the Python-list mailing list