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
# ...
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.
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