What is the preferred way to write Python doc string?
"""
or "
In the book Dive Into Python, the author provides the following example:
def buildConnectionString(params): """Build a connection string from a dictionary of parameters. Returns string."""
In another chapter, the author provides another example:
def stripnulls(data): "strip whitespace and nulls" return data.replace("\00", "").strip()
Both syntax work. The only difference to me is that """
allows us to write multi-line doc.
Is there any difference other than that?
Enclose strings containing both single and double quotes such that no escaping is needed. Enclose multi-line strings.
To create strings that span multiple lines, triple single quotes ''' or triple double quotes """ are used to enclose the string. ''' This string is on multiple lines within three single quotes on either side. ''' """ This string is on multiple lines within three double quotes on either side.
Using single and double quotes are equivalent. The only difference is when we use an apostrophe or additional quotation marks inside the string, in which case we may need to escape those punctuation(s) using a backslash ( \ ). For example: print("That's great!") print('That\'s great!')
Triple quoted strings are used as comment by many developers but it is actually not a comment, it is similar to regular strings in python but it allows the string to be in multi-line. You will find no official reference for triple quoted strings to be a comment.
From the PEP8 Style Guide:
PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, e.g.:
"""Return a foobang Optional plotz says to frobnicate the bizbaz first. """
For one liner docstrings, it's okay to keep the closing """ on the same line.
PEP 257 recommends using triple quotes, even for one-line docstrings:
Note that not even the Python standard library itself follows these recommendations consistently. For example,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With