** kwargs 매개 변수를 문서화하는 올바른 방법은 무엇입니까?
저는 sphinx 와 autodoc 플러그인을 사용하여 Python 모듈에 대한 API 문서를 생성하고 있습니다. 특정 매개 변수를 잘 문서화하는 방법을 볼 수는 있지만 매개 변수를 문서화하는 방법의 예는 찾을 수 없습니다 **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"""..."""
이것을 "원시"문서화 문자열하고, 따라서 유지하기 위해 필요 \*
(스핑크스는 리터럴로 데리러 그대로을 *
"강조"의 아닌 시작).
선택한 형식 (괄호로 묶인 유형 및 m- 대시로 구분 된 설명이있는 글 머리 기호 목록)은 단순히 Sphinx에서 제공하는 자동 형식과 일치하는 것입니다.
"키워드 인수"섹션을 기본 "매개 변수"섹션처럼 보이게 만드는 이러한 노력을 한 후에는 처음부터 자체 매개 변수 섹션을 롤링하는 것이 더 쉬울 것 같습니다 (다른 답변에 따라). ,하지만 **kwargs
이미 Sphinx를 사용하고있는 경우 개념 증명으로 보완을위한 멋진 모습을 얻을 수있는 한 가지 방법 입니다.
Sphinx에서 파싱 한 Google 스타일 독 스트링
면책 조항 : 테스트되지 않았습니다.
의이 컷 아웃에서 스핑크스 문서화 문자열의 예 는 *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 예 해당 설명서에서 스핑크스에 대한이. 특히 그들은 다음을 보여줍니다.
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 스타일 가이드를 가리킬 것 입니다. 그들의 독 스트링 예는 그들이 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는 하위 프로세스 관리 문서를 참조하는 데 허용되는 답변에 대해 질문이 있습니다. 모듈을 가져 오면 inspect.getsource를 통해 모듈 독 스트링을 빠르게 볼 수 있습니다.
Silent Ghost의 권장 사항을 사용하는 파이썬 인터프리터의 예 :
>>> import subprocess
>>> import inspect
>>> import print inspect.getsource(subprocess)
물론 도움말 기능을 통해 모듈 문서를 볼 수도 있습니다. 예를 들어 help (subprocess)
나는 개인적으로 kwargs에 대한 하위 프로세스 독 스트링의 팬이 아니지만 Google 예제와 마찬가지로 Sphinx 문서 예제에 표시된대로 kwarg를 별도로 나열하지 않습니다.
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()
I'm including this answer to A-B-B's question because it's worth noting that you can review any module's source or documentation this way for insights and inspiration for commenting your code.
If anyone else is looking for some valid syntax.. Here's an example docstring. This is just how I did it, I hope it's useful to you, but I can't claim that it's compliant with anything in particular.
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
This depends on the style of documentation you use, but if you are using the numpydoc style it is recommend to document **kwargs
using Other Parameters
.
For example, following quornian's example:
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}``.
"""
Note especially that it is recommended to give the defaults of kwargs, since these are not obvious from the function signature.
참고 URL : https://stackoverflow.com/questions/1137161/what-is-the-correct-way-to-document-a-kwargs-parameter
'IT박스' 카테고리의 다른 글
자바 : 코드의 전체 디렉토리 구조를 어떻게 컴파일 할 수 있습니까? (0) | 2020.10.16 |
---|---|
프리 포크 웹 서버 모델은 정확히 무엇입니까? (0) | 2020.10.15 |
Java에서 개체 모니터의 의미는 무엇입니까? (0) | 2020.10.15 |
Eclipse에서 자동으로 ant build.xml 파일을 생성하는 방법은 무엇입니까? (0) | 2020.10.15 |
IntelliJ IDEA에서 예외 발생기 강조 (0) | 2020.10.15 |