Forced naming of parameters in Python

后端 未结 11 1298
日久生厌
日久生厌 2020-11-27 12:15

In Python you may have a function definition:

def info(object, spacing=10, collapse=1)

which could be called in any of the following ways:<

11条回答
  •  天涯浪人
    2020-11-27 12:51

    As other answers say, changing function signatures is a bad idea. Either add new parameters to the end, or fix every caller if arguments are inserted.

    If you still want to do it, use a function decorator and the inspect.getargspec function. It would be used something like this:

    @require_named_args
    def info(object, spacing=10, collapse=1):
        ....
    

    Implementation of require_named_args is left as an exercise for the reader.

    I would not bother. It will be slow every time the function is called, and you will get better results from writing code more carefully.

提交回复
热议问题