Any reason to put code before the docstring in Python?
Asked Answered
N

1

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
  # ...
Nettles answered 6/5, 2016 at 9:35 Comment(0)
R
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.

Raybin answered 6/5, 2016 at 9:39 Comment(5)
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)?Nettles
@AlexTereshenkov: carelessness and "oh sry i didnt know that" may qualify as special cases.Holcman
@AlexTereshenkov: there is never a reason to do this. Consider it a bug.Raybin
Terrific, thanks. Wanted to check first before editing others' code to not mess things up.Nettles
@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).Raybin

© 2022 - 2024 — McMap. All rights reserved.