Triple-double quote v.s. Double quote

Question:

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("0", "").strip()

Both syntax work. The only difference to me is that """ allows us to write multi-line doc.

Are there any differences other than that?

Asked By: Mingyu

||

Answers:

They’re both strings, so there is no difference. The preferred style is triple double quotes (PEP 257):

For consistency, always use """triple double quotes""" around docstrings.

Use r"""raw triple double quotes""" if you use any backslashes in your docstrings. For Unicode docstrings, use u"""Unicode triple-quoted strings""".

Answered By: Blender

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:

  • Triple quotes are used even though the string fits on one line. This
    makes it easy to later expand it.

Note that not even the Python standard library itself follows these recommendations consistently. For example,

Answered By: unutbu

No, not really. If you are writing to a file, using triple quotes may be ideal, because you don’t have to use “n” in order to go a line down. Just make sure the quotes you start and end with are the same type(Double or Triple quotes). Here is a reliable resource if you have any more questions:

http://docs.python.org/release/1.5.1p1/tut/strings.html

Answered By: user2514631

I use triple-double quotes for a long SQL query to improve the readability and not to scroll right to see it as shown below:

query = """
        SELECT count(*) 
        FROM (SELECT * 
              FROM student  
              WHERE grade = 2 AND major = 'Computer Science' 
              FOR UPDATE) 
        AS result;
        """

And, if using double quotes for the SQL query above, the readability is worse and you will need to scroll right to see it as shown below:

query = "SELECT count(*) FROM (SELECT * FROM student WHERE grade = 2 AND major = 'Computer Science' FOR UPDATE) AS result;"
Answered By: Kai – Kazuya Ito
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.