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

LaundroMat Laundro at gmail.com
Wed Oct 4 04:15:35 EDT 2006


Rob De Almeida wrote:

> LaundroMat 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..
>
> If you *absolutely* want to pass a value and you don't know the default
> value (otherwise you could just pass it):
>
> >>> import inspect
> >>> v = inspect.getargspec(f)[3][0] # first default value
> >>> f(v)
> 2

I have in fact a bunch of functions that all pass similar information
to one main function. That function takes (amongst others) a template
variable. If it's not being passed, it is set to a default value by the
function called upon.

For the moment, whenever a function calls the main function, I check
whether the calling function has the template variable set:

>>> if template:
>>>    return mainFunction(var, template)
>>> else:
>>>    return mainFunction(var)

Now, I thought this isn't the cleanest way to do things; so I was
looking for ways to initialize the template variable, so that I could
always return mainFunction(var, template). mainFunction() would then
assign the default value to template.

>From your answers, this seems to be impossible. The minute my variable
is initialised, there's no way I can have mainFunction() assign a value
without explicitly asking it to do so.

I guess the best way would then be to change mainFunction from:
>>> def mainFunction(var, template='base'):
to
>>> def mainFunction(var, template):
>>> if len(template)=0:
>>>    template = 'base'

and have the calling functions call mainFunction (var, template) and
initialise template to ''.

I still have that nagging feeling nicer code could be written to solve
this, but I won't try to lose any sleep over it.

Thanks for all the replies.




More information about the Python-list mailing list