Setting the default value of a function input to equal another input in Python

后端 未结 3 1614
天涯浪人
天涯浪人 2021-02-05 07:13

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 bo         


        
3条回答
  •  滥情空心
    2021-02-05 07:41

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

    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
    

    If None could be a valid value, the solution is to either use *args/**kwargs magic as in carl's answer, or use a sentinel object. Libraries that do this include attrs and Marshmallow, and in my opinion it's much cleaner and likely faster.

    missing = object()
    
    def example(a, b, c=missing):
        if c is missing:
            c = a
        ...
    

    The only way for c is missing to be true is for c to be exactly that dummy object you created there.

提交回复
热议问题