5

I see in some other people's Python code that they paste some checks before the docstring of the function; something like this:

def func(args):
  if x_version != 1.7:
    return
  """docstring is here"""
  # function body code
  # ...

Are there any cases when you should or have to put some code before the docstring to workaround anything? Are there any special cases that this style had to be introduced or it's always just a bad styling and thus must be fixed to something like this?

def func(args):
  """docstring is here"""
  if x_version != 1.7:
    return
  # function body code
  # ...
Alex Tereshenkov
  • 3,340
  • 8
  • 36
  • 61

1 Answers1

11

Python will only pick up a docstring if it is the first statement in the function body. Putting code before it means the string is just ignored altogether:

>>> def func(args):
...   if x_version != 1.7:
...     return
...   """docstring is here"""
...
>>> func.__doc__ is None
True

You should never do this if you want the docstring to actually have any effect.

From the Python reference documentation:

A string literal appearing as the first statement in the function body is transformed into the function’s __doc__ attribute and therefore the function’s docstring.

Bold emphasis mine.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • That's true. I was using the `inspect` module to see if there were functions with no docstrings and that's how I found the function with the moved docstring :) so you can't think of any special case when you have to put any Python code before the docstring (understanding that the docstring will not be available for others in IDEs etc)? – Alex Tereshenkov May 06 '16 at 09:40
  • 1
    @AlexTereshenkov: carelessness and "oh sry i didnt know that" may qualify as special cases. – Jongware May 06 '16 at 09:48
  • @AlexTereshenkov: there is **never** a reason to do this. Consider it a bug. – Martijn Pieters May 06 '16 at 09:49
  • Terrific, thanks. Wanted to check first before editing others' code to not mess things up. – Alex Tereshenkov May 06 '16 at 10:05
  • @AlexTereshenkov: some people do use triple-quoted strings to 'comment out' a section of code, since CPython will completely ignore stand-alone string literals if not the first statement, but I generally advice people to use normal commenting instead (your editor can help). – Martijn Pieters May 06 '16 at 10:15