3

I'm currently reading python code that is using strings as comments. For example, here's a function

def xyz(x):
    """This is a function that does a thing.
    Pretty cool, right?"""
    return 0

What's the point of using strings as comments? It seems really strange. The code compiles, but it's very confusing.

5
  • 1
    Its noT string comments! Its basically multi line comments ! Commented Mar 2, 2017 at 3:44
  • 4
    It's called a docstring and it is interpreted by python's help/documentation system, try help(xyz). Usually you would describe the types of arguments this function takes and what to expect as a return. Commented Mar 2, 2017 at 3:45
  • en.wikipedia.org/wiki/Docstring Commented Mar 2, 2017 at 3:45
  • It seems strange to me that the return has a semi-colon Commented Mar 2, 2017 at 3:45
  • @cricket_007 I'm still getting used to the syntax :) Commented Mar 2, 2017 at 3:46

2 Answers 2

2
"""This is a function that does a thing.
Pretty cool, right?"""

This is called docstring. Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.

Example

Docstrings can be accessed from the interpreter and from Python programs using the __doc__ attribute:

print(xyz.__doc__)

It outputs:

This is a function that does a thing.
    Pretty cool, right?

Another usage:

from pydoc import help
print(help(xyz))

It outputs:

Help on function xyz in module __main__:

xyz(x)
    This is a function that does a thing.
    Pretty cool, right?
Sign up to request clarification or add additional context in comments.

Comments

2

They're called docstrings, and they're used for documenting your code. Tools and builtins like help() also inspect docstrings, so they're not just for readers of the code, but also users of your code.

1 Comment

I didn't know that help() was a function, thank you, that's helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.