有没有理由把代码放在Python的docstring之前?

我在其他人的
Python代码中看到他们在函数的docstring之前粘贴了一些检查;这样的事情:

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

是否有任何情况需要或者必须在docstring之前放置一些代码来解决任何问题?是否有任何特殊情况需要引入这种风格,或者它总是只是一个糟糕的造型,因此必须修复到这样的东西?

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

最佳答案 如果它是函数体中的第一个语句,Python将只选取一个docstring.在它之前放置代码意味着字符串完全被忽略:

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

如果您希望docstring实际上有任何效果,则不应该这样做.

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.

大胆强调我的.

点赞