How can I understand symbols used in arguments of methods in Python Documentation?

Question:

I am finding it difficult to understand Python Documentation. So, there are going to be multiple questions in this question.

for e.g.:

>>> help(str)
.
.
.

center(self, width, fillchar=' ', /)
    ...

count(...)
    S.count(sub[, start[, end]]) -> int

    ...
.
.
.

(1) What does / mean in the argument of center?

(2) What does [ and ] mean in the argument of count?

(3) Is sub[ a single argument (as separated by commas) or the whole thing sub[, start[, end]] a single argument? Meaning is , start[, end] inside the square bracket of sub similarly for start?

(4) Why are some things defined as just width (in center) but some with equal sign as fillchar=' '?

(5) Not related to Python Documentation, but why is self not written in the argument of count?

PS: You can also share relevant links for the answers to particular questions.

Asked By: TheMaskedTitan

||

Answers:

Question 1

While declaring arguments, the / key means that everything to the left of it must be a positional argument, while everything to the right can be a positional as well as a keyword argument. See this or PEP 570 for more details.

Questions 2 and 3

That means the arguments inside the brackets can be provided only if the outer left argument is given. In this case, sub[, start[, end]], start can be given only if you have provided sub. Similarly, to give end, you should provide sub and start both. Also, the square brackets around the parameters mean that they are optional.

Question 4

You can define default arguments in Python by assigning them a default value using the assignment (=) operator of the form keywordname=value in the function declaration. In this case, the fillchar argument is optional, so if it is not provided, the function will use ' ' as the fillchar value.

Question 5

These are called instance methods. Instance methods are called by using the syntax object_name.method_name(). When calling it this way, the instance method receives the object or instance as an argument, named self by convention. However, self should appear in the function definition of count(...) (in those three dots).

Answered By: Luis G.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.