Why do Python function docs include the comma after the bracket for optional args?

后端 未结 5 1584
灰色年华
灰色年华 2020-12-03 04:08

The format of the function signatures in the Python docs is a bit confusing. What is the significance in putting the comma after the open bracket, rather than before? What

相关标签:
5条回答
  • 2020-12-03 04:45

    The brackets mean that you can leave out the part between them. So if the docs would be written the way you suggest, it would imply that you can write RegexObject.match(string,,) by leaving everything in brackets. Or RegexObject.match(string,,endpos) by just leaving out the second one. But you can't. If you leave out endpos, you also have to leave out the comma before it. And if you leave out pos, you have to leave out the comma before it as well as endpos. So it's written in a way that makes that clear.

    0 讨论(0)
  • 2020-12-03 04:48

    Because otherwise the correct syntax would be to include the comma even if you are ignoring the arguments. The parts inside the square brackets are optional, so by moving the commas out of the square brackets, they are no longer optional. For example, to call the function below with only a string:

    RegexObject.match(string, [pos], [endpos])
    

    I would have to do:

    RegexObject.match("foobar",,)
    

    But, that isn't very elegant.

    0 讨论(0)
  • 2020-12-03 04:48

    If you think about the brackets enclosing all optional components of the argument list, it makes more sense. Essentially, anything inside brackets may be left out at the discretion of the user.

    0 讨论(0)
  • 2020-12-03 04:55

    The square bracket means that the contents are optional, but everything outside of square brackets is compulsory.

    With your notation:

    RegexObject.match(string, [pos], [endpos])
    

    I would expect to have to write:

    r.match("foo",,)
    

    The nesting is required because if you supply the third parameter then you must also supply the second parameter even though it is an optional parameter. The following non-nested alternative would be ambiguous:

    RegexObject.match(string[, pos][, endpos])
    
    0 讨论(0)
  • 2020-12-03 04:57

    The open bracket indicates an optional argument. If the comma were outside the bracket, you would have to type it even if you didn't want to use the pos argument (for example).

    0 讨论(0)
提交回复
热议问题