What value should be passed to make a function use the default argument value?
Nick Craig-Wood
nick at craig-wood.com
Wed Oct 4 06:30:04 EDT 2006
LaundroMat <Laundro at gmail.com> wrote:
> 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 ''.
None is the traditional value to use for value not present, then you'd
get this for the function
def mainFunction(var, template=None):
if template is None:
template = 'base'
And this for the calling bit
if not_set_properly(template):
template = None
return mainFunction(var, template)
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list