Forced naming of parameters in Python

后端 未结 11 1276
日久生厌
日久生厌 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 13:09

    Update:

    I realized that using **kwargs would not solve the problem. If your programmers change function arguments as they wish, one could, for example, change the function to this:

    def info(foo, **kwargs):
    

    and the old code would break again (because now every function call has to include the first argument).

    It really comes down to what Bryan says.


    (...) people might be adding parameters between spacing and collapse (...)

    In general, when changing functions, new arguments should always go to the end. Otherwise it breaks the code. Should be obvious.
    If someone changes the function so that the code breaks, this change has to be rejected.
    (As Bryan says, it is like a contract)

    (...) sometimes it's not always clear as to what needs to go in.

    By looking at the signature of the function (i.e def info(object, spacing=10, collapse=1) ) one should immediately see that every argument that has not a default value, is mandatory.
    What the argument is for, should go into the docstring.


    Old answer (kept for completeness):

    This is probably not a good solution:

    You can define functions this way:

    def info(**kwargs):
        ''' Some docstring here describing possible and mandatory arguments. '''
        spacing = kwargs.get('spacing', 15)
        obj = kwargs.get('object', None)
        if not obj:
           raise ValueError('object is needed')
    

    kwargs is a dictionary that contains any keyword argument. You can check whether a mandatory argument is present and if not, raise an exception.

    The downside is, that it might not be that obvious anymore, which arguments are possible, but with a proper docstring, it should be fine.

提交回复
热议问题