2015-12-17 5 views
6

Есть ли способ прокомментировать параметры функции, чтобы сделать их распознанными библиотекой pydoc?Как прокомментировать параметры для pydoc

i.e что такое docstring для pydoc?

+0

Возможный дубликат [Как документировать метод с параметром (ами)?] (HTTPS: //stackoverflow.com/questions/9195455/how-to-document-a-method-with-parameters) –

+0

@ Steven Vascellaro. В отличие от возможного дубликата, этот вопрос специфичен для библиотеки pydoc. – PatriceG

ответ

14

pydoc не распознает «структурированные» элементы в docstrings, он просто выводит docstring как есть. См. Пример PEP 0257.

Если вы хотите «форматную» документацию, вы должны использовать другой генератор документации, такие как Sphinx, например

Параметры функции должны быть задокументированы в функциях строке документации. Вот пример, взятый из this answer:

""" 
This example module shows various types of documentation available for use 
with pydoc. To generate HTML documentation for this module issue the 
command: 

    pydoc -w foo 

""" 

class Foo(object): 
    """ 
    Foo encapsulates a name and an age. 
    """ 
    def __init__(self, name, age): 
     """ 
     Construct a new 'Foo' object. 

     :param name: The name of foo 
     :param age: The ageof foo 
     :return: returns nothing 
     """ 
     self.name = name 
     self.age 

def bar(baz): 
    """ 
    Prints baz to the display. 
    """ 
    print baz 

if __name__ == '__main__': 
    f = Foo('John Doe', 42) 
    bar("hello world") 

Вот еще более явный пример, если вы хотите воспользоваться преимуществами текста с измененной структурой с большим количеством дескрипторов параметров, таких как :type param: или :rtype: принятых from here

""" 
The ``obvious`` module 
====================== 

Use it to import very obvious functions. 

:Example: 

>>> from obvious import add 
>>> add(1, 1) 
2 

This is a subtitle 
------------------- 

You can say so many things here ! You can say so many things here ! 
You can say so many things here ! You can say so many things here ! 
You can say so many things here ! You can say so many things here ! 
You can say so many things here ! You can say so many things here ! 

This is another subtitle 
------------------------ 

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 

""" 

def add(a, b): 
    """ 
    Adds two numbers and returns the result. 

    This add two real numbers and return a real result. You will want to 
    use this function in any place you would usually use the ``+`` operator 
    but requires a functional equivalent. 

    :param a: The first number to add 
    :param b: The second number to add 
    :type a: int 
    :type b: int 
    :return: The result of the addition 
    :rtype: int 

    :Example: 

    >>> add(1, 1) 
    2 
    >>> add(2.1, 3.4) # all int compatible types work 
    5.5 

    .. seealso:: sub(), div(), mul() 
    .. warnings:: This is a completly useless function. Use it only in a 
       tutorial unless you want to look like a fool. 
    .. note:: You may want to use a lambda function instead of this. 
    .. todo:: Delete this function. Then masturbate with olive oil. 
    """ 
    return a + b 

You также могут использовать разные форматы docstring (например, Google или Numpy), , которые я рекомендую !!!, чтобы сделать ваши документы более четкими.

Надеюсь, это поможет!

+0

Спасибо. Я уже пробовал первую docstring. Однако параметр: param не распознается pydoc и отображается как другие комментарии в сгенерированном html-документе. – PatriceG

+0

Pydoc не распознает «структурированные» элементы в docstrings, он просто выводит docstring как есть. См. [PEP 0257] (https://www.python.org/dev/peps/pep-0257/) для примера. Если вы хотите использовать эту функцию, вам придется использовать другой генератор документации, как я уже сказал выше. Извините за путаницу, я отредактирую свой ответ – Ire

+0

Итак, наконец, ответ: «он не будет работать с pydoc, я мог бы использовать Sphinx, если я захочу это сделать». Правильно ? – PatriceG

2

Другой пример

#!/usr/bin/env python 

""" 
Module documentation 
A small example of comments usage 
""" 

# regular comment, 
# will not visible by pydoc 
spam = 40 


def square(x): 
    """ 
    this function will return square(x) value 
    :param x: any number 
    :return: example doc for return 
    """ 
    return x ** 2 

import abc 


class ListInherited: 
    """ 
     Class ListInherited doc example 
     This class use dir() function for list instance attributes 
    """ 

    def __init__(self, arg1): 
     """ 
     my constructor 
     :param arg1: example value 
     :return: 
     """ 
     self.arg1 = arg1 

    def __str__(self): 
     """ 
     to string conversion 
     :return: 
     """ 
     tup = (self.__class__.__name__, id(self), self.attr_names()) 
     return '<Instance of %s, address %s:\n%s>' % tup 

    def attr_names(self): 
     """ 
     get attribute names 
     :return: string 
     """ 
     result = '' 

     for attr in dir(self): 
      if attr[:2] == '__' and attr[-2:] == '__': # skip "build-in" 
       result += '\t name %s=<>\n' % attr 
      else: 
       result += '\t name %s=%s\n' % (attr, getattr(self, attr)) 
     return result 

    @staticmethod 
    def my_static_method(count): 
     """ 
     static method comment example 
     :param count: 
     :return: 
     """ 
     return "Hello, I'm static" * count 


if __name__ == "__main__": 
    import test3 

    x = 33 
    y = test3.square(x) 

    print(test3.__doc__) 
    print(test3.square.__doc__) 

    instance = ListInherited(1) 
    print(instance.__doc__) 

В питона консоли

>>> import test3 
>>> help(test3) 

Выход:

Help on module test3: 

NAME 
    test3 

FILE 
    /home/mrdinkelman/PycharmProjects/testproject27/test3.py 

DESCRIPTION 
    Module documentation 
    A small example of comments usage 

CLASSES 
    ListInherited 

    class ListInherited 
    | Class ListInherited doc example 
    | This class use dir() function for list instance attributes 
    | 
    | Methods defined here: 
    | 
    | __init__(self, arg1) 
    |  my constructor 
    |  :param arg1: example value 
    |  :return: 
    | 
    | __str__(self) 
    |  to string conversion 
    |  :return: 
    | 
    | attr_names(self) 
    |  get attribute names 
    |  :return: string 
    | 
    | ---------------------------------------------------------------------- 
    | Static methods defined here: 
    | 
    | my_static_method(count) 
    |  static method comment example 
    |  :param count: 
    |  :return: 

FUNCTIONS 
    square(x) 
     this function will return square(x) value 
     :param x: any number 
     :return: example doc for return 

DATA 
    spam = 40 
+0

Спасибо. Тем не менее, ключевое слово «: param» распознано help()? Кажется, он печатает его как любой другой комментарий. – PatriceG

Смежные вопросы