Forced naming of parameters in Python

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

    You can do that in a way that works in both Python 2 and Python 3, by making a "bogus" first keyword argument with a default value that will not occur "naturally". That keyword argument can be preceded by one or more arguments without value:

    _dummy = object()
    
    def info(object, _kw=_dummy, spacing=10, collapse=1):
        if _kw is not _dummy:
            raise TypeError("info() takes 1 positional argument but at least 2 were given")
    

    This will allow:

    info(odbchelper)        
    info(odbchelper, collapse=0)        
    info(spacing=15, object=odbchelper)
    

    but not:

    info(odbchelper, 12)                
    

    If you change the function to:

    def info(_kw=_dummy, spacing=10, collapse=1):
    

    then all arguments must have keywords and info(odbchelper) will no longer work.

    This will allow you to position additional keyword arguments any place after _kw, without forcing you to put them after the last entry. This often makes sense, e.g. grouping thing logically or arranging keywords alphabetically can help with maintenance and development.

    So there is no need to revert to using def(**kwargs) and losing the signature information in your smart editor. Your social contract is to provide certain information, by forcing (some of them) to require keywords, the order these are presented in, has become irrelevant.

提交回复
热议问题