Skip to content Skip to sidebar Skip to footer

Python Optional Function Argument To Default To Another Argument's Value

I want to define a function with some optional arguments, let's say A (mandatory) and B (optional). When B is not given, I want it to take the same value as A. How could I do that?

Solution 1:

You shall do this inside of your function.

Taking your original function:

deffoo(A, B=A):
    do_something()

try something like:

deffoo(A, B=None):
    if B isNone:
        B = A
    do_something()

Important thing is, that function default values for function arguments are given at the time, the function is defined.

When you call the function with some value for A, it is too late as the B default value was already assigned and lives in function definition.

Solution 2:

You could do it like this. If B has a value of None then assign it from A

deffoo(A, B=None):
    if B isNone:
        B = A

    print'A = %r' % A
    print'B = %r' % B

Post a Comment for "Python Optional Function Argument To Default To Another Argument's Value"