Can triple quotation be used instead of a #

Im in exercise 25 and trying to debug but oddly what I think is bugs does not seem to be any bug.

There is a definition that looks like

def break_words(stuff):
    """This function will break up words for us"""
    words = stuff.split(' ')
    return words

I would think that

"""This function will break up words for us""" 

give an error as it’s just a ‘a floating string’ inside a definition.
But I get no error.
Wondering if I can use the triple quotation mark instead # for commenting?

The triple quote string at the top of a module, or a class or function definition (as in this case) is something special. It’s a doc string that provides information about the object or it’s intended usage.

Type that ‘break_words’ definition code into a python console and then use:

help(break_words)

See what happens. Note, use Ctrl-Z to exit afterwards.

Alternatively if you are using an IDE, after the definition, type out the call to the function break_words() but hover over it. The IDE will display the same help info.

Good programmers include these doc strings all over the show as they are massively helpful when you are unfamiliar with the code you are using.

The comment requires you to read the code, whereas a doc string provide documentation during implementation, (potentially where the code is encapsulated).

1 Like

Hi @gpkesley thanks for this.

But why would you not always just use triple string instead of #-Comments?

Is there a way to disable multiple lines in the code in one go instead of have to comment out all lines with #

Checkout Guido’s tweet on the difference: https://twitter.com/gvanrossum/status/112670605505077248

Doc strings generate code, whereas comments do not. If you consider the idea that well-written code is well commented, explaining it, then you really do not want all those coding comments to be generated into your ‘help’ or ‘man’ files.

You might also use comments like:

# TODO: remember to refactor function - it's isn't efficient

But you certainly don’t want that in your help files. (Actually your IDE would notice the TODO comment and add it to a list for you to work on).

The purpose of the doc strings is partially commenting, but also Python attaches them to the function so you can print out docs about the function. Like this:

$ python
Python 2.7.10 (default, Oct  6 2017, 22:29:07) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(list.reverse)

Help on method_descriptor:

reverse(...)
    L.reverse() -- reverse *IN PLACE*

Try typing help(ex25.break_words) and it should print whatever you put into the doc string there.

1 Like