Search code examples
pythondocstring

Why wasn't the string at the top of this function printed?


I encountered the following function in a tutorial. When I call the function, "This prints a passed string into this function" isn't printed. Why does the function not print this piece of text when called?

def printme(str):
   "This prints a passed string into this function"
   print str
   return

# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Solution

  • What you’re seeing there is a document string, or docstring in short.

    A docstring is a string that is supposed to document the thing it is attached to. In your case, it is attached to a function, and as such is supposed to document the function. You can also have docstrings for classes and modules.

    You create docstrings by simply placing a string on its own as the very first thing in a function (or class, or module). The interpreter will then use it as a docstring and make it available in special the __doc__ attribute:

    >>> def printme( str ):
            "This prints a passed string into this function"
            print str
    
    >>> printme.__doc__
    'This prints a passed string into this function'
    

    Docstrings are also used by the help() function:

    >>> help(printme)
    Help on function printme in module __main__:
    
    printme(str)
        This prints a passed string into this function
    

    The common practice for docstrings, to make it clear that they are supposed to be actual docstrings and not just misplaced “proper” strings, is to use triple quotes. Triple quotes are used to create multi-line strings which in addition allows docstrings to be multi-line too:

    def printme (str):
        '''
        Print the string passed in the `str` argument to the
        standard output. This is essentially just a wrapper
        around Python’s built-in `print`.
        '''
        print(str)
    

    Various docstring conventions are also described in PEP 257.