In Python, can I specify a function argument’s default in terms of other arguments?

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'

Leave a Comment