Search code examples
pythoncommentspep8docstring

Is it a good practice to use triple quotes to create "docstrings" in non-standard contexts?


I am looking at someone's code which has this kind of "docstrings" all over the place:

SLEEP_TIME_ON_FAILURE = 5
"""Time to keep the connection open in case of failure."""

SOCKET_TIMEOUT = 15
"""Socket timeout for inherited socket."""

...

As per the Python documentation, docstrings are applicable only in the context of the beginning of a module, class, or a method.

What is the implication of the above non-standard practice? Why does Python allow this? Doesn't this have performance impact?


Solution

  • As far as Python is concerned, these aren't docstrings. They're just string literals used as expression statements. You can do that - you can use any valid Python expression as its own statement. Python doesn't care whether the expression actually does anything. For a string on its own line, the only performance impact is a very small amount of extra work at bytecode compilation time; there's no impact at runtime, since these strings get optimized out.

    Some documentation generators do look at these strings. For example, the very common Sphinx autodoc extension will parse these strings to document whatever is directly above them. Check whether you're using anything like that before you change the code.