In Python, can I specify a function argument's default in terms of other arguments?
Solution 1:
As @Ignacio says, you can't do this. In your latter example, you might have a situation where None
is a valid value for arg2
. If this is the case, you can use a sentinel value:
sentinel = object()
def myfunc(arg1, arg2=sentinel):
if arg2 is sentinel:
arg2 = arg1
print (arg1, arg2)
myfunc("foo") # Prints 'foo foo'
myfunc("foo", None) # Prints 'foo None'
Solution 2:
Not really. The other argument names don't exist until the function is actually entered.
Solution 3:
The second way is fine in my opinion: it is exactly clear what you do, and for all those who will come after you and read the code. While there is a slight overhead in documenting the default behavior, the use of 'None' or any other to make your function generate a default value is very common. Putting logic inside the function calls would certainly not be commendable in my opinion, it could become very complex very soon. So just leave it in the function body, where all the code is.