سؤال

أنا استخدم أبو الهول ومكون إضافي Autodoc لتوليد وثائق API لوحدات Python الخاصة بي. في حين أستطيع أن أرى كيفية توثيق معلمات محددة بشكل جيد، لا يمكنني العثور على مثال حول كيفية توثيق **kwargs معامل.

هل لدى أي شخص مثال جيد بطريقة واضحة لتوثيق هذه؟

هل كانت مفيدة؟

المحلول

أظن subprocessمستندات module. هو مثال جيد. إعطاء قائمة شاملة لجميع المعلمات ل أعلى / فئة الوالدين. وبعد ثم فقط الرجوع إلى تلك القائمة لجميع الأحداث الأخرى **kwargs.

نصائح أخرى

بعد العثور على هذا السؤال، استقرت على ما يلي، وهو صالح SPHINX ويعمل بشكل جيد إلى حد ما:

def some_function(first, second="two", **kwargs):
    r"""Fetches and returns this thing

    :param first:
        The first parameter
    :type first: ``int``
    :param second:
        The second parameter
    :type second: ``str``
    :param \**kwargs:
        See below

    :Keyword Arguments:
        * *extra* (``list``) --
          Extra stuff
        * *supplement* (``dict``) --
          Additional content

    """

ال r"""...""" مطلوب لجعل هذا docstring "الخام" وبالتالي الحفاظ على \* سليمة (أبو الهول لالتقاط كحرفي * وليس بداية "التركيز").

يعد التنسيق المختار (القائمة النقطية ذات النوع القياسي الوصف المنفصل عن الأنواع) لمطابقة التنسيق الآلي الذي توفره SPHINX.

بمجرد أن تذهب إلى هذا الجهد لجعل قسم "وسيطات الكلمات الرئيسية" يشبه قسم "المعلمات" الافتراضية، يبدو أنه قد يكون من الأسهل لف قسم المعلمات الخاصة بك من البداية (حسب بعض الإجابات الأخرى) ، ولكن كدليل على المفهوم هذه طريقة واحدة لتحقيق نظرة لطيفة عن التكميلية **kwargs إذا كنت تستخدم بالفعل أبو الهول.

تحليل DocStrings من Google بواسطة Sphinx

إخلاء المسئولية: لم يتم اختبارها.

من هذا الانقطاع من sphinx docstring مثال, ، ال *args و **kwargs وغادر غير مؤكد:

def module_level_function(param1, param2=None, *args, **kwargs):
    """
    ...

    Args:
        param1 (int): The first parameter.
        param2 (Optional[str]): The second parameter. Defaults to None.
            Second line of description should be indented.
        *args: Variable length argument list.
        **kwargs: Arbitrary keyword arguments.

أود يقترح الحل التالي للانحدار:

    """
    Args:
        param1 (int): The first parameter.
        param2 (Optional[str]): The second parameter. Defaults to None.
            Second line of description should be indented.
        *param3 (int): description
        *param4 (str): 
        ...
        **key1 (int): description 
        **key2 (int): description 
        ...

لاحظ كيف، Optional غير مطلوب ل **key الحجج.

غير ذلك, ، يمكنك محاولة سرد القوائم بشكل صريح تحت Other Parameters و **kwargs تحت Keyword Args (انظر تحليلها أقسام):

    """
    Args:
        param1 (int): The first parameter.
        param2 (Optional[str]): The second parameter. Defaults to None.
            Second line of description should be indented.

    Other Parameters:
        param3 (int): description
        param4 (str): 
        ...

    Keyword Args:
        key1 (int): description 
        key2 (int): description 
        ...

هناك مثال DOCTSTRING ل sphinx في وثائقهم. على وجه التحديد عرض ما يلي:

def public_fn_with_googley_docstring(name, state=None):
"""This function does something.

Args:
   name (str):  The name to use.

Kwargs:
   state (bool): Current state to be in.

Returns:
   int.  The return code::

      0 -- Success!
      1 -- No good.
      2 -- Try again.

Raises:
   AttributeError, KeyError

A really great idea.  A way you might use me is

>>> print public_fn_with_googley_docstring(name='foo', state=None)
0

BTW, this always returns 0.  **NEVER** use with :class:`MyPublicClass`.

"""
return 0

على الرغم من أنك سئلت عن صراحة، أود أن أشير أيضا إلى دليل Google Python Style. وبعد يبدو أن مثال Factring الخاص بهم يعني أنهم لا يدعون KWARGS على وجه التحديد. (Other_silly_variable = لا شيء)

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""Fetches rows from a Bigtable.

Retrieves rows pertaining to the given keys from the Table instance
represented by big_table.  Silly things may happen if
other_silly_variable is not None.

Args:
    big_table: An open Bigtable Table instance.
    keys: A sequence of strings representing the key of each table row
        to fetch.
    other_silly_variable: Another optional variable, that has a much
        longer name than the other args, and which does nothing.

Returns:
    A dict mapping keys to the corresponding table row data
    fetched. Each row is represented as a tuple of strings. For
    example:

    {'Serak': ('Rigel VII', 'Preparer'),
     'Zim': ('Irk', 'Invader'),
     'Lrrr': ('Omicron Persei 8', 'Emperor')}

    If a key from the keys argument is missing from the dictionary,
    then that row was not found in the table.

Raises:
    IOError: An error occurred accessing the bigtable.Table object.
"""
pass

لدى ABB سؤال حول الجواب المقبول من الإشارة إلى الوثائق الإدارية الفرعية. إذا قمت باستيراد وحدة نمطية، يمكنك بسهولة رؤية DocStrings الوحدة النمطية عبر تفتيش.

مثال من مترجم الثعبان باستخدام توصية الأشباح الصامتة:

>>> import subprocess
>>> import inspect
>>> import print inspect.getsource(subprocess)

بالطبع يمكنك أيضا عرض وثائق الوحدة النمطية عن طريق وظيفة المساعدة. على سبيل المثال المساعدة (Subprocess)

أنا لست شخصيا من محبي DocProcess Substring for Kwargs كمثال، ولكن مثل مثال Google لا يسرد Kwargs بشكل منفصل كما هو موضح في مثال مستندات SPHINX.

def call(*popenargs, **kwargs):
"""Run command with arguments.  Wait for command to complete, then
return the returncode attribute.

The arguments are the same as for the Popen constructor.  Example:

retcode = call(["ls", "-l"])
"""
return Popen(*popenargs, **kwargs).wait()

أشمل هذه الإجابة على سؤال ABB لأنه تجدر الإشارة إلى أنه يمكنك مراجعة أي مصدر أو وثائق الوحدة النمطية بهذه الطريقة للرؤى والإلهام للتعليق على التعليمات البرمجية الخاصة بك.

إذا كان أي شخص آخر يبحث عن بناء الجملة ساري المفعول .. إليك مثال DocString. هذا هو مجرد كيف فعلت ذلك، آمل أن يكون مفيدا لك، لكنني لا أستطيع أن أدعي أنه متوافق مع أي شيء على وجه الخصوص.

def bar(x=True, y=False):
    """
    Just some silly bar function.

    :Parameters:
      - `x` (`bool`) - dummy description for x
      - `y` (`string`) - dummy description for y
    :return: (`string`) concatenation of x and y.
    """
    return str(x) + y

def foo (a, b, **kwargs):
    """
    Do foo on a, b and some other objects.

    :Parameters:
      - `a` (`int`) - A number.
      - `b` (`int`, `string`) - Another number, or maybe a string.
      - `\**kwargs` - remaining keyword arguments are passed to `bar`

    :return: Success
    :rtype: `bool`
    """
    return len(str(a) + str(b) + bar(**kwargs)) > 20

هذا يعتمد على نمط الوثائق التي تستخدمها، ولكن إذا كنت تستخدم numpydoc. النمط هو يوصي بالوثيقة **kwargs استخدام Other Parameters.

على سبيل المثال، بعد مثال Quornian:

def some_function(first, second="two", **kwargs):
    """Fetches and returns this thing

    Parameters
    ----------
    first : `int`
        The first parameter
    second : `str`, optional
        The second parameter

    Other Parameters
    ----------------
    extra : `list`, optional
        Extra stuff. Default ``[]``.
    suplement : `dict`, optional
        Additional content. Default ``{'key' : 42}``.
    """

ملاحظة خاصة أنه ينصح بإعطاء الإعدادات الافتراضية من KWARGS، لأن هذه ليست واضحة من توقيع الوظيفة.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top