Skip to content

Commit 148accc

Browse files
committed
Format docstrings in a consistent style
1 parent 8783e65 commit 148accc

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+1598
-1696
lines changed

doc/en/reference.rst

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ Mark a test function as using the given fixture names.
187187

188188
.. py:function:: pytest.mark.usefixtures(*names)
189189
190-
:param args: the names of the fixture to use, as strings
190+
:param args: The names of the fixture to use, as strings.
191191

192192

193193
.. _`pytest.mark.xfail ref`:
@@ -206,8 +206,10 @@ Marks a test function as *expected to fail*.
206206
Condition for marking the test function as xfail (``True/False`` or a
207207
:ref:`condition string <string conditions>`). If a bool, you also have
208208
to specify ``reason`` (see :ref:`condition string <string conditions>`).
209-
:keyword str reason: Reason why the test function is marked as xfail.
210-
:keyword Exception raises: Exception subclass expected to be raised by the test function; other exceptions will fail the test.
209+
:keyword str reason:
210+
Reason why the test function is marked as xfail.
211+
:keyword Type[Exception] raises:
212+
Exception subclass expected to be raised by the test function; other exceptions will fail the test.
211213
:keyword bool run:
212214
If the test function should actually be executed. If ``False``, the function will always xfail and will
213215
not be executed (useful if a function is segfaulting).
@@ -221,7 +223,7 @@ Marks a test function as *expected to fail*.
221223
a new release of a library fixes a known bug).
222224

223225

224-
custom marks
226+
Custom marks
225227
~~~~~~~~~~~~
226228

227229
Marks are created dynamically using the factory object ``pytest.mark`` and applied as a decorator.
@@ -470,7 +472,7 @@ caplog
470472
.. autofunction:: _pytest.logging.caplog()
471473
:no-auto-options:
472474

473-
This returns a :class:`_pytest.logging.LogCaptureFixture` instance.
475+
Returns a :class:`_pytest.logging.LogCaptureFixture` instance.
474476

475477
.. autoclass:: _pytest.logging.LogCaptureFixture
476478
:members:
@@ -488,7 +490,7 @@ monkeypatch
488490
.. autofunction:: _pytest.monkeypatch.monkeypatch()
489491
:no-auto-options:
490492

491-
This returns a :class:`MonkeyPatch` instance.
493+
Returns a :class:`MonkeyPatch` instance.
492494

493495
.. autoclass:: _pytest.monkeypatch.MonkeyPatch
494496
:members:

src/_pytest/_argcomplete.py

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
"""allow bash-completion for argparse with argcomplete if installed
2-
needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail
1+
"""Allow bash-completion for argparse with argcomplete if installed.
2+
3+
Needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail
34
to find the magic string, so _ARGCOMPLETE env. var is never set, and
4-
this does not need special code.
5+
this does not need special code).
56
67
Function try_argcomplete(parser) should be called directly before
78
the call to ArgumentParser.parse_args().
@@ -10,8 +11,7 @@
1011
arguments specification, in order to get "dirname/" after "dirn<TAB>"
1112
instead of the default "dirname ":
1213
13-
optparser.add_argument(Config._file_or_dir, nargs='*'
14-
).completer=filescompleter
14+
optparser.add_argument(Config._file_or_dir, nargs='*').completer=filescompleter
1515
1616
Other, application specific, completers should go in the file
1717
doing the add_argument calls as they need to be specified as .completer
@@ -20,35 +20,43 @@
2020
2121
SPEEDUP
2222
=======
23+
2324
The generic argcomplete script for bash-completion
24-
(/etc/bash_completion.d/python-argcomplete.sh )
25+
(/etc/bash_completion.d/python-argcomplete.sh)
2526
uses a python program to determine startup script generated by pip.
2627
You can speed up completion somewhat by changing this script to include
2728
# PYTHON_ARGCOMPLETE_OK
2829
so the the python-argcomplete-check-easy-install-script does not
2930
need to be called to find the entry point of the code and see if that is
30-
marked with PYTHON_ARGCOMPLETE_OK
31+
marked with PYTHON_ARGCOMPLETE_OK.
3132
3233
INSTALL/DEBUGGING
3334
=================
35+
3436
To include this support in another application that has setup.py generated
3537
scripts:
36-
- add the line:
38+
39+
- Add the line:
3740
# PYTHON_ARGCOMPLETE_OK
38-
near the top of the main python entry point
39-
- include in the file calling parse_args():
41+
near the top of the main python entry point.
42+
43+
- Include in the file calling parse_args():
4044
from _argcomplete import try_argcomplete, filescompleter
41-
, call try_argcomplete just before parse_args(), and optionally add
42-
filescompleter to the positional arguments' add_argument()
45+
Call try_argcomplete just before parse_args(), and optionally add
46+
filescompleter to the positional arguments' add_argument().
47+
4348
If things do not work right away:
44-
- switch on argcomplete debugging with (also helpful when doing custom
49+
50+
- Switch on argcomplete debugging with (also helpful when doing custom
4551
completers):
4652
export _ARC_DEBUG=1
47-
- run:
53+
54+
- Run:
4855
python-argcomplete-check-easy-install-script $(which appname)
4956
echo $?
50-
will echo 0 if the magic line has been found, 1 if not
51-
- sometimes it helps to find early on errors using:
57+
will echo 0 if the magic line has been found, 1 if not.
58+
59+
- Sometimes it helps to find early on errors using:
5260
_ARGCOMPLETE=1 _ARC_DEBUG=1 appname
5361
which should throw a KeyError: 'COMPLINE' (which is properly set by the
5462
global argcomplete script).
@@ -63,29 +71,29 @@
6371

6472

6573
class FastFilesCompleter:
66-
"Fast file completer class"
74+
"""Fast file completer class."""
6775

6876
def __init__(self, directories: bool = True) -> None:
6977
self.directories = directories
7078

7179
def __call__(self, prefix: str, **kwargs: Any) -> List[str]:
72-
"""only called on non option completions"""
80+
# Only called on non option completions.
7381
if os.path.sep in prefix[1:]:
7482
prefix_dir = len(os.path.dirname(prefix) + os.path.sep)
7583
else:
7684
prefix_dir = 0
7785
completion = []
7886
globbed = []
7987
if "*" not in prefix and "?" not in prefix:
80-
# we are on unix, otherwise no bash
88+
# We are on unix, otherwise no bash.
8189
if not prefix or prefix[-1] == os.path.sep:
8290
globbed.extend(glob(prefix + ".*"))
8391
prefix += "*"
8492
globbed.extend(glob(prefix))
8593
for x in sorted(globbed):
8694
if os.path.isdir(x):
8795
x += "/"
88-
# append stripping the prefix (like bash, not like compgen)
96+
# Append stripping the prefix (like bash, not like compgen).
8997
completion.append(x[prefix_dir:])
9098
return completion
9199

src/_pytest/_code/code.py

Lines changed: 43 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,8 @@ def __eq__(self, other):
7171

7272
@property
7373
def path(self) -> Union[py.path.local, str]:
74-
"""Return a path object pointing to source code (or a str in case
75-
of OSError / non-existing file).
76-
"""
74+
"""Return a path object pointing to source code, or an ``str`` in
75+
case of ``OSError`` / non-existing file."""
7776
if not self.raw.co_filename:
7877
return ""
7978
try:
@@ -412,15 +411,16 @@ def from_exc_info(
412411
exc_info: Tuple["Type[_E]", "_E", TracebackType],
413412
exprinfo: Optional[str] = None,
414413
) -> "ExceptionInfo[_E]":
415-
"""Returns an ExceptionInfo for an existing exc_info tuple.
414+
"""Return an ExceptionInfo for an existing exc_info tuple.
416415
417416
.. warning::
418417
419418
Experimental API
420419
421-
:param exprinfo: a text string helping to determine if we should
422-
strip ``AssertionError`` from the output, defaults
423-
to the exception message/``__str__()``
420+
:param exprinfo:
421+
A text string helping to determine if we should strip
422+
``AssertionError`` from the output. Defaults to the exception
423+
message/``__str__()``.
424424
"""
425425
_striptext = ""
426426
if exprinfo is None and isinstance(exc_info[1], AssertionError):
@@ -436,15 +436,16 @@ def from_exc_info(
436436
def from_current(
437437
cls, exprinfo: Optional[str] = None
438438
) -> "ExceptionInfo[BaseException]":
439-
"""Returns an ExceptionInfo matching the current traceback.
439+
"""Return an ExceptionInfo matching the current traceback.
440440
441441
.. warning::
442442
443443
Experimental API
444444
445-
:param exprinfo: a text string helping to determine if we should
446-
strip ``AssertionError`` from the output, defaults
447-
to the exception message/``__str__()``
445+
:param exprinfo:
446+
A text string helping to determine if we should strip
447+
``AssertionError`` from the output. Defaults to the exception
448+
message/``__str__()``.
448449
"""
449450
tup = sys.exc_info()
450451
assert tup[0] is not None, "no current exception"
@@ -459,7 +460,7 @@ def for_later(cls) -> "ExceptionInfo[_E]":
459460
return cls(None)
460461

461462
def fill_unfilled(self, exc_info: Tuple["Type[_E]", _E, TracebackType]) -> None:
462-
"""fill an unfilled ExceptionInfo created with for_later()"""
463+
"""Fill an unfilled ExceptionInfo created with ``for_later()``."""
463464
assert self._excinfo is None, "ExceptionInfo was already filled"
464465
self._excinfo = exc_info
465466

@@ -560,7 +561,8 @@ def getrepr(
560561
Show locals per traceback entry.
561562
Ignored if ``style=="native"``.
562563
563-
:param str style: long|short|no|native|value traceback style
564+
:param str style:
565+
long|short|no|native|value traceback style.
564566
565567
:param bool abspath:
566568
If paths should be changed to absolute or left unchanged.
@@ -575,7 +577,8 @@ def getrepr(
575577
:param bool truncate_locals:
576578
With ``showlocals==True``, make sure locals can be safely represented as strings.
577579
578-
:param bool chain: if chained exceptions in Python 3 should be shown.
580+
:param bool chain:
581+
If chained exceptions in Python 3 should be shown.
579582
580583
.. versionchanged:: 3.9
581584
@@ -635,7 +638,7 @@ class FormattedExcinfo:
635638
astcache = attr.ib(default=attr.Factory(dict), init=False, repr=False)
636639

637640
def _getindent(self, source: "Source") -> int:
638-
# figure out indent for given source
641+
# Figure out indent for the given source.
639642
try:
640643
s = str(source.getstatement(len(source) - 1))
641644
except KeyboardInterrupt:
@@ -696,7 +699,7 @@ def get_exconly(
696699
) -> List[str]:
697700
lines = []
698701
indentstr = " " * indent
699-
# get the real exception information out
702+
# Get the real exception information out.
700703
exlines = excinfo.exconly(tryshort=True).split("\n")
701704
failindent = self.fail_marker + indentstr[1:]
702705
for line in exlines:
@@ -722,8 +725,7 @@ def repr_locals(self, locals: Mapping[str, object]) -> Optional["ReprLocals"]:
722725
str_repr = saferepr(value)
723726
else:
724727
str_repr = safeformat(value)
725-
# if len(str_repr) < 70 or not isinstance(value,
726-
# (list, tuple, dict)):
728+
# if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)):
727729
lines.append("{:<10} = {}".format(name, str_repr))
728730
# else:
729731
# self._line("%-10s =\\" % (name,))
@@ -801,16 +803,17 @@ def repr_traceback(self, excinfo: ExceptionInfo) -> "ReprTraceback":
801803
def _truncate_recursive_traceback(
802804
self, traceback: Traceback
803805
) -> Tuple[Traceback, Optional[str]]:
804-
"""
805-
Truncate the given recursive traceback trying to find the starting point
806-
of the recursion.
806+
"""Truncate the given recursive traceback trying to find the starting
807+
point of the recursion.
807808
808-
The detection is done by going through each traceback entry and finding the
809-
point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``.
809+
The detection is done by going through each traceback entry and
810+
finding the point in which the locals of the frame are equal to the
811+
locals of a previous frame (see ``recursionindex()``).
810812
811-
Handle the situation where the recursion process might raise an exception (for example
812-
comparing numpy arrays using equality raises a TypeError), in which case we do our best to
813-
warn the user of the error and show a limited traceback.
813+
Handle the situation where the recursion process might raise an
814+
exception (for example comparing numpy arrays using equality raises a
815+
TypeError), in which case we do our best to warn the user of the
816+
error and show a limited traceback.
814817
"""
815818
try:
816819
recursionindex = traceback.recursionindex()
@@ -855,8 +858,8 @@ def repr_excinfo(self, excinfo: ExceptionInfo) -> "ExceptionChainRepr":
855858
excinfo_._getreprcrash() if self.style != "value" else None
856859
) # type: Optional[ReprFileLocation]
857860
else:
858-
# fallback to native repr if the exception doesn't have a traceback:
859-
# ExceptionInfo objects require a full traceback to work
861+
# Fallback to native repr if the exception doesn't have a traceback:
862+
# ExceptionInfo objects require a full traceback to work.
860863
reprtraceback = ReprTracebackNative(
861864
traceback.format_exception(type(e), e, None)
862865
)
@@ -907,7 +910,7 @@ def toterminal(self, tw: TerminalWriter) -> None:
907910
# This class is abstract -- only subclasses are instantiated.
908911
@attr.s(**{ATTRS_EQ_FIELD: False}) # type: ignore
909912
class ExceptionRepr(TerminalRepr):
910-
# Provided by in subclasses.
913+
# Provided by subclasses.
911914
reprcrash = None # type: Optional[ReprFileLocation]
912915
reprtraceback = None # type: ReprTraceback
913916

@@ -934,7 +937,7 @@ class ExceptionChainRepr(ExceptionRepr):
934937
def __attrs_post_init__(self) -> None:
935938
super().__attrs_post_init__()
936939
# reprcrash and reprtraceback of the outermost (the newest) exception
937-
# in the chain
940+
# in the chain.
938941
self.reprtraceback = self.chain[-1][0]
939942
self.reprcrash = self.chain[-1][1]
940943

@@ -966,7 +969,7 @@ class ReprTraceback(TerminalRepr):
966969
entrysep = "_ "
967970

968971
def toterminal(self, tw: TerminalWriter) -> None:
969-
# the entries might have different styles
972+
# The entries might have different styles.
970973
for i, entry in enumerate(self.reprentries):
971974
if entry.style == "long":
972975
tw.line("")
@@ -1009,7 +1012,7 @@ class ReprEntry(TerminalRepr):
10091012
style = attr.ib(type="_TracebackStyle")
10101013

10111014
def _write_entry_lines(self, tw: TerminalWriter) -> None:
1012-
"""Writes the source code portions of a list of traceback entries with syntax highlighting.
1015+
"""Write the source code portions of a list of traceback entries with syntax highlighting.
10131016
10141017
Usually entries are lines like these:
10151018
@@ -1091,8 +1094,8 @@ class ReprFileLocation(TerminalRepr):
10911094
message = attr.ib(type=str)
10921095

10931096
def toterminal(self, tw: TerminalWriter) -> None:
1094-
# filename and lineno output for each entry,
1095-
# using an output format that most editors understand
1097+
# Filename and lineno output for each entry, using an output format
1098+
# that most editors understand.
10961099
msg = self.message
10971100
i = msg.find("\n")
10981101
if i != -1:
@@ -1167,10 +1170,10 @@ def getfslineno(obj: object) -> Tuple[Union[str, py.path.local], int]:
11671170
return code.path, code.firstlineno
11681171

11691172

1170-
# relative paths that we use to filter traceback entries from appearing to the user;
1171-
# see filter_traceback
1173+
# Relative paths that we use to filter traceback entries from appearing to the user;
1174+
# see filter_traceback.
11721175
# note: if we need to add more paths than what we have now we should probably use a list
1173-
# for better maintenance
1176+
# for better maintenance.
11741177

11751178
_PLUGGY_DIR = py.path.local(pluggy.__file__.rstrip("oc"))
11761179
# pluggy is either a package or a single module depending on the version
@@ -1189,14 +1192,14 @@ def filter_traceback(entry: TracebackEntry) -> bool:
11891192
* internal traceback from pytest or its internal libraries, py and pluggy.
11901193
"""
11911194
# entry.path might sometimes return a str object when the entry
1192-
# points to dynamically generated code
1193-
# see https://bitbucket.org/pytest-dev/py/issues/71
1195+
# points to dynamically generated code.
1196+
# See https://bitbucket.org/pytest-dev/py/issues/71.
11941197
raw_filename = entry.frame.code.raw.co_filename
11951198
is_generated = "<" in raw_filename and ">" in raw_filename
11961199
if is_generated:
11971200
return False
11981201
# entry.path might point to a non-existing file, in which case it will
1199-
# also return a str object. see #1133
1202+
# also return a str object. See #1133.
12001203
p = py.path.local(entry.path)
12011204
return (
12021205
not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR)

0 commit comments

Comments
 (0)