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

后端 未结 3 1376
南方客
南方客 2020-12-01 15:55

Suppose I have a python function that takes two arguments, but I want the second arg to be optional, with the default being whatever was passed as the first argument. So, I

3条回答
  •  时光取名叫无心
    2020-12-01 16:15

    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'
    

提交回复
热议问题