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 07:14:42 EDT 2006


On 2006-10-04, Georg Brandl <g.brandl-nospam at gmx.net> wrote:
> Antoon Pardon wrote:
>> On 2006-10-04, Paul Rubin <http> wrote:
>>> Antoon Pardon <apardon at forel.vub.ac.be> writes:
>>>> Now in this case you could start by assigning arg the value 1 and
>>>> eliminate the if test. However that only works if you know the
>>>> default value for the argument. What he seems to be asking for
>>>> is if there is an object, (let as call it Default), that would
>>>> make code like:
>>>> 
>>>>   def f(var=1):
>>>> 
>>>> Equivallent to:
>>>> 
>>>>   def f(var=Default)
>>>>     if var is Default)
>>>>       var = 1
>>>
>>> Oh, I see.  Yes, the OP should just use a distinct default value
>>> instead of 1.  I usually do this with
>>>
>>>    sentinel = object()
>>>
>>>    def f(var=sentinel):
>>>      if var is sentinel:
>>>        # f was called without an arg 
>> 
>> But that can only work if you are the author of f. Take the
>> following code:
>> 
>>   def myrepeat(obj, times = xxx):
>>     return itertools.repeat(obj, times)
>> 
>> What value do I have to substitue for xxx, so that myrepeat
>> will have the exact same function as itertools.repeat?
>
> There's no possible value. You'll have to write this like

Yes, that was the point I wanted to make. 

> def myrepeat(obj, times=None):
>      if times is None:
>          return itertools.repeat(obj)
>      else:
>          return itertools.repeat(obj, times)
>
> Many functions implemented in C have this behavior.

Which is a pity and IMO makes the documentation of these
functions a bit problematic. Take the itertool.repeat
documentation:

repeat(object[, times])
    Make an iterator that returns object over and over again. Runs
    indefinitely unless the times argument is specified. ...

My first impression from this, is that it is possible to call
this as follows:

  repeat(None, times = 5)

But that doesn't work either.

> For all functions written in Python, you can look up the default
> value in the source.

That wont help much if you would like something like the following:

   def fun(f):

     arg = Default
     try:
       arg = Try_Processing()
     except Nothing_To_Process:
       pass
     f(arg)

-- 
Antoon Pardon



More information about the Python-list mailing list