views:

75

answers:

3

Hello,

Consider the following function, which does not work in Python, but I will use to explain what I need to do.

def exampleFunction(a, b, c = a):
    ...function body...

That is I want to assign to variable c the same value that variable a would take, unless an alternative value is specified. The above code does not work in python. Is there a way to do this?

Thank you.

+10  A: 
def exampleFunction(a, b, c = None):
    if c is None:
        c = a
    ...function body...

The default value for the keyword argument can't be a variable (if it is, it's converted to a fixed value when the function is defined.) Commonly used to pass arguments to a main function:

def main(argv=None):
    if argv is None:
        argv = sys.argv
Nick T
Exactly. Default arguments are set in stone once the function is defined.
delnan
A: 

One approach is something like:

def foo(a, b, c=None):
    c = a if c is None else c
    # do something
ars
+8  A: 

This general pattern is probably the best and most readable:

def exampleFunction(a, b, c = None):
    if c is None:
        c = a
    ...

You have to be careful that None is not a valid state for c.

If you want to support 'None' values, you can do something like this:

def example(a, b, *args, **kwargs):
    if 'c' in kwargs:
        c = kwargs['c']
    elif len(args) > 0:
        c = args[0]
    else:
        c = a
carl
+1 for being mentioning that `None` can't be a valid state for `c` for the `c=None` trick to work.
aaronasterling