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

五迷三道 提交于 2019-11-27 02:25:52

问题


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 is the significance of nesting the brackets?

How they are:

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

I would expect one of the following:

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

回答1:


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])



回答2:


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).




回答3:


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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/2120507/why-do-python-function-docs-include-the-comma-after-the-bracket-for-optional-arg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!