What is the difference between using triple double quotes (""") and hash sign (#) to comment in Python?

Question:

I am currently learning Python, previously I was with Java and the comments were nothing more than as shown below:

    //Para una sola línea de código en Java

    /* Para poder realizar un comentario
       en varias líneas en Java*/

Some time ago I used Python to develop an exam, I created a web system ( following tutorials ) with the help of Django , comments with 3 double quotes ( """ ) appeared within the worksheets, as shown below:

    """
    Django settings for libreria project.
    Generated by 'django-admin startproject' using Django 2.1.2.
    For more information on this file, see
    https://docs.djangoproject.com/en/2.1/topics/settings/
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.1/ref/settings/
    """

I have taken the above directly from a file on my system

And on the other hand:

#Para un comentario de una sola línea en `Python`

Now I find that to make a comment on several lines is:

#Para poder realizar un comentario
#de varias líneas, al colocar una almohadilla
#al final de la frase el IDE genera la almohadilla 
#izquierda automáticamente# 

Where only pads are used for comments, whether they are single line or more.


Then:

  • Do both triple double quotes and hash marks work for multi-line comments?
  • Is there a difference between using one or the other when commenting inside the code?
  • Are there rules to use one or the other (depends on something?)?

Answer:

The comments, strictly speaking, are made with the hash exclusively.

  • They can be block comments :

     # Esto es un comentario de bloque en Python # que hace uso de varias lineas. # # Esto es otro párrafo del comentario de bloque if foo == 8: pass

    By convention, the following rules are followed:

    • They apply to part or all of the code that follows (block).
    • They are indented at the same level as the code they comment on.
    • Each line of a block comment begins with a # and a space.
    • Paragraphs within a block comment are separated by a line containing only a #
  • Line comments :

     foo = 4 # Soy un comentario inline

    By convention:

    • They are defined on the same line as a commenting statement.
    • They must be separated by at least two spaces from the statement they comment on.
    • They must start with a # followed by a space.

Triple quotes (both double """ and single ''' ) are a way to create string literals that can also be multiline:

cad = """Soy una cadena
con varias
líneas
"""

print(cad)
Soy una cadena con varias líneas

We can also create string literals with just a single and double quote in Python:

cad = "Hola"
cad = 'Hola'

There is no difference between the two forms, but if one is used to specify the literal, the other can be used inside the literal without escaping:

cad = "Hola tiene una 'h' y una 'l'"

Although it is common to see "comments" in Python code using triple-quoted literals without assigning to any variables, they are not true comments . What is true is that the (non-interactive) interpreter ignores these lines (without assignment) when generating the bytecode and interpreting it, so they virtually become comments, without really being and without being the correct way to do it. .

There is an exception to take into account, if this literal is declared in the first line after defining a function, method or class , they have special functionality, they are what are known as docstring or documentation strings . They are strings that serve as documentation and usage guidance for that object. The conventions for documentation strings are defined in PEP 257 .

Summarizing:

  • The first line must be a brief summary of the object's purpose, must not explicitly state the object's name or type, and must always begin with a capital letter and end with a period.

  • If only the previous line exists, no spaces should be added before or after it. The quotes must be closed on the same line.

  • It should not be the function signature, this is done by introspection and would be redundant. The function signature should only be specified if it is written in C/C++ ( C/C++ API ), where introspection does not reach.

  • If there are more lines, the second line should be blank, visually separating the summary from the rest of the description.

  • The extra lines provide information about the object's calling conventions, its side effects, return, etc.

  • When there is more than one line, the closing triple quote must stand alone on the final line, preferably preceded by a blank line.

  • Although a string literal declared with single or double quotes can be used, by convention (and because it is usually more than one line) triple quotes are used even if they are on a single line.


def sin(x: float, unidad: str = "radian") -> float:
    """Retorna el seno de x (en radianes).

    Argumentos keywords:
    unidad -- radian o grado (radian por defecto)

    """
    pass

def sqrt(x: float) -> float:
    """Retorna la raiz cuadrada de x."""
    pass

This string (in addition to helping the code to be understood by humans reading it) can be accessed via the special __doc__ attribute of the object, and this method can be used by the buitin help , used when the -h / --help argument is specified. when invoking a script in the terminal, by the own development environments and code editors to show the pop-up help while writing code and in general by any other documentation generator or parser:

>>> help(sin) Help on function sin in module __main__: sin(x: float, unidad: str = 'radian') -> float Retorna el seno de x (en radianes). Argumentos keywords: unidad -- radian o grado (radian por defecto)

All packages, scripts, modules, methods, classes and functions for public use should have their docstring defined. They aren't needed in non-public methods, but it doesn't hurt to have a comment describing what they do.


To finish clarifying, in case someone at this point wonders why Django uses triple quotes for comments… The example you put is not a comment, it is in fact the docstring for the modules that Django automatically generates. In this specific case it is the default docstring for settings.py , just as for functions, methods, etc. documentation parsers make use of it, including help , the -h / --help command line argument, etc. :

>>> import settings
>>> help(settings)

Help on module settings:

NAME
    settings - Django settings for ExampleApp project.

DESCRIPTION
    Generated by 'django-admin startproject' using Django 1.9.6.

    For more information on this file, see
    https://docs.djangoproject.com/en/1.9/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.9/ref/settings/

DATA
    ALLOWED_HOSTS = []
    AUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_val...
    ....
Scroll to Top