all Python 3inspectfunction
inspect.getcomments()
source code
Returns the # comment lines right above a function, class or method definition (for a module, at the top of the file). A source file is required.
Syntax
inspect.getcomments(object)
It reads the source file, not the object: for built-ins and for code created by exec(), in the interactive shell or under python -c, it quietly returns None instead of raising. A blank line between the comment and the def breaks the link. The docstring is not included; getdoc() returns that.
Examples
import inspect
class Cart:
# Итог с учётом скидки.
# Скидка — в процентах.
def total(self, discount):
pass
print(repr(inspect.getcomments(Cart.total)))
# → '# Итог с учётом скидки.\n# Скидка — в процентах.\n'
import inspect
namespace = {}
exec('# комментарий\ndef dyn(): pass', namespace)
print(inspect.getcomments(namespace['dyn'])) # → None — исходного файла нет
print(inspect.getcomments(len)) # → None
See also
Open in the full glossarydocs.python.orgReport an inaccuracy