Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason to put code before the docstring in Python?

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
  # ...
like image 647
Alex Tereshenkov Avatar asked Dec 18 '22 17:12

Alex Tereshenkov


1 Answers

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.

like image 173
Martijn Pieters Avatar answered Dec 21 '22 06:12

Martijn Pieters