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

Georg Brandl g.brandl-nospam at gmx.net
Wed Oct 4 12:55:16 CEST 2006


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

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.

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

Georg



More information about the Python-list mailing list