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")
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.
It does get executed, however evaluating and the never using a string is effectively a no-op. The reason it works in the REPL is beacuse the REPL is the REPL, that is the read eval print loop. The print step does not exists in ordinary execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With