Skip to content

Commit 92126fd

Browse files
committed
Format docstrings in a consistent style
1 parent d756b4a commit 92126fd

Some content is hidden

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

55 files changed

+1601
-1697
lines changed

doc/en/reference.rst

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

183183
.. py:function:: pytest.mark.usefixtures(*names)
184184
185-
:param args: the names of the fixture to use, as strings
185+
:param args: The names of the fixture to use, as strings.
186186

187187
.. note::
188188

@@ -209,8 +209,10 @@ Marks a test function as *expected to fail*.
209209
Condition for marking the test function as xfail (``True/False`` or a
210210
:ref:`condition string <string conditions>`). If a bool, you also have
211211
to specify ``reason`` (see :ref:`condition string <string conditions>`).
212-
:keyword str reason: Reason why the test function is marked as xfail.
213-
:keyword Exception raises: Exception subclass expected to be raised by the test function; other exceptions will fail the test.
212+
:keyword str reason:
213+
Reason why the test function is marked as xfail.
214+
:keyword Type[Exception] raises:
215+
Exception subclass expected to be raised by the test function; other exceptions will fail the test.
214216
:keyword bool run:
215217
If the test function should actually be executed. If ``False``, the function will always xfail and will
216218
not be executed (useful if a function is segfaulting).
@@ -224,7 +226,7 @@ Marks a test function as *expected to fail*.
224226
a new release of a library fixes a known bug).
225227

226228

227-
custom marks
229+
Custom marks
228230
~~~~~~~~~~~~
229231

230232
Marks are created dynamically using the factory object ``pytest.mark`` and applied as a decorator.
@@ -473,7 +475,7 @@ caplog
473475
.. autofunction:: _pytest.logging.caplog()
474476
:no-auto-options:
475477

476-
This returns a :class:`_pytest.logging.LogCaptureFixture` instance.
478+
Returns a :class:`_pytest.logging.LogCaptureFixture` instance.
477479

478480
.. autoclass:: _pytest.logging.LogCaptureFixture
479481
:members:
@@ -491,7 +493,7 @@ monkeypatch
491493
.. autofunction:: _pytest.monkeypatch.monkeypatch()
492494
:no-auto-options:
493495

494-
This returns a :class:`MonkeyPatch` instance.
496+
Returns a :class:`MonkeyPatch` instance.
495497

496498
.. autoclass:: _pytest.monkeypatch.MonkeyPatch
497499
: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:
@@ -420,15 +419,16 @@ def from_exc_info(
420419
exc_info: Tuple["Type[_E]", "_E", TracebackType],
421420
exprinfo: Optional[str] = None,
422421
) -> "ExceptionInfo[_E]":
423-
"""Returns an ExceptionInfo for an existing exc_info tuple.
422+
"""Return an ExceptionInfo for an existing exc_info tuple.
424423
425424
.. warning::
426425
427426
Experimental API
428427
429-
:param exprinfo: a text string helping to determine if we should
430-
strip ``AssertionError`` from the output, defaults
431-
to the exception message/``__str__()``
428+
:param exprinfo:
429+
A text string helping to determine if we should strip
430+
``AssertionError`` from the output. Defaults to the exception
431+
message/``__str__()``.
432432
"""
433433
_striptext = ""
434434
if exprinfo is None and isinstance(exc_info[1], AssertionError):
@@ -444,15 +444,16 @@ def from_exc_info(
444444
def from_current(
445445
cls, exprinfo: Optional[str] = None
446446
) -> "ExceptionInfo[BaseException]":
447-
"""Returns an ExceptionInfo matching the current traceback.
447+
"""Return an ExceptionInfo matching the current traceback.
448448
449449
.. warning::
450450
451451
Experimental API
452452
453-
:param exprinfo: a text string helping to determine if we should
454-
strip ``AssertionError`` from the output, defaults
455-
to the exception message/``__str__()``
453+
:param exprinfo:
454+
A text string helping to determine if we should strip
455+
``AssertionError`` from the output. Defaults to the exception
456+
message/``__str__()``.
456457
"""
457458
tup = sys.exc_info()
458459
assert tup[0] is not None, "no current exception"
@@ -467,7 +468,7 @@ def for_later(cls) -> "ExceptionInfo[_E]":
467468
return cls(None)
468469

469470
def fill_unfilled(self, exc_info: Tuple["Type[_E]", _E, TracebackType]) -> None:
470-
"""fill an unfilled ExceptionInfo created with for_later()"""
471+
"""Fill an unfilled ExceptionInfo created with ``for_later()``."""
471472
assert self._excinfo is None, "ExceptionInfo was already filled"
472473
self._excinfo = exc_info
473474

@@ -568,7 +569,8 @@ def getrepr(
568569
Show locals per traceback entry.
569570
Ignored if ``style=="native"``.
570571
571-
:param str style: long|short|no|native|value traceback style
572+
:param str style:
573+
long|short|no|native|value traceback style.
572574
573575
:param bool abspath:
574576
If paths should be changed to absolute or left unchanged.
@@ -583,7 +585,8 @@ def getrepr(
583585
:param bool truncate_locals:
584586
With ``showlocals==True``, make sure locals can be safely represented as strings.
585587
586-
:param bool chain: if chained exceptions in Python 3 should be shown.
588+
:param bool chain:
589+
If chained exceptions in Python 3 should be shown.
587590
588591
.. versionchanged:: 3.9
589592
@@ -643,7 +646,7 @@ class FormattedExcinfo:
643646
astcache = attr.ib(default=attr.Factory(dict), init=False, repr=False)
644647

645648
def _getindent(self, source: "Source") -> int:
646-
# figure out indent for given source
649+
# Figure out indent for the given source.
647650
try:
648651
s = str(source.getstatement(len(source) - 1))
649652
except KeyboardInterrupt:
@@ -704,7 +707,7 @@ def get_exconly(
704707
) -> List[str]:
705708
lines = []
706709
indentstr = " " * indent
707-
# get the real exception information out
710+
# Get the real exception information out.
708711
exlines = excinfo.exconly(tryshort=True).split("\n")
709712
failindent = self.fail_marker + indentstr[1:]
710713
for line in exlines:
@@ -730,8 +733,7 @@ def repr_locals(self, locals: Mapping[str, object]) -> Optional["ReprLocals"]:
730733
str_repr = saferepr(value)
731734
else:
732735
str_repr = safeformat(value)
733-
# if len(str_repr) < 70 or not isinstance(value,
734-
# (list, tuple, dict)):
736+
# if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)):
735737
lines.append("{:<10} = {}".format(name, str_repr))
736738
# else:
737739
# self._line("%-10s =\\" % (name,))
@@ -809,16 +811,17 @@ def repr_traceback(self, excinfo: ExceptionInfo) -> "ReprTraceback":
809811
def _truncate_recursive_traceback(
810812
self, traceback: Traceback
811813
) -> Tuple[Traceback, Optional[str]]:
812-
"""
813-
Truncate the given recursive traceback trying to find the starting point
814-
of the recursion.
814+
"""Truncate the given recursive traceback trying to find the starting
815+
point of the recursion.
815816
816-
The detection is done by going through each traceback entry and finding the
817-
point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``.
817+
The detection is done by going through each traceback entry and
818+
finding the point in which the locals of the frame are equal to the
819+
locals of a previous frame (see ``recursionindex()``).
818820
819-
Handle the situation where the recursion process might raise an exception (for example
820-
comparing numpy arrays using equality raises a TypeError), in which case we do our best to
821-
warn the user of the error and show a limited traceback.
821+
Handle the situation where the recursion process might raise an
822+
exception (for example comparing numpy arrays using equality raises a
823+
TypeError), in which case we do our best to warn the user of the
824+
error and show a limited traceback.
822825
"""
823826
try:
824827
recursionindex = traceback.recursionindex()
@@ -863,8 +866,8 @@ def repr_excinfo(self, excinfo: ExceptionInfo) -> "ExceptionChainRepr":
863866
excinfo_._getreprcrash() if self.style != "value" else None
864867
) # type: Optional[ReprFileLocation]
865868
else:
866-
# fallback to native repr if the exception doesn't have a traceback:
867-
# ExceptionInfo objects require a full traceback to work
869+
# Fallback to native repr if the exception doesn't have a traceback:
870+
# ExceptionInfo objects require a full traceback to work.
868871
reprtraceback = ReprTracebackNative(
869872
traceback.format_exception(type(e), e, None)
870873
)
@@ -915,7 +918,7 @@ def toterminal(self, tw: TerminalWriter) -> None:
915918
# This class is abstract -- only subclasses are instantiated.
916919
@attr.s(**{ATTRS_EQ_FIELD: False}) # type: ignore
917920
class ExceptionRepr(TerminalRepr):
918-
# Provided by in subclasses.
921+
# Provided by subclasses.
919922
reprcrash = None # type: Optional[ReprFileLocation]
920923
reprtraceback = None # type: ReprTraceback
921924

@@ -942,7 +945,7 @@ class ExceptionChainRepr(ExceptionRepr):
942945
def __attrs_post_init__(self) -> None:
943946
super().__attrs_post_init__()
944947
# reprcrash and reprtraceback of the outermost (the newest) exception
945-
# in the chain
948+
# in the chain.
946949
self.reprtraceback = self.chain[-1][0]
947950
self.reprcrash = self.chain[-1][1]
948951

@@ -974,7 +977,7 @@ class ReprTraceback(TerminalRepr):
974977
entrysep = "_ "
975978

976979
def toterminal(self, tw: TerminalWriter) -> None:
977-
# the entries might have different styles
980+
# The entries might have different styles.
978981
for i, entry in enumerate(self.reprentries):
979982
if entry.style == "long":
980983
tw.line("")
@@ -1017,7 +1020,7 @@ class ReprEntry(TerminalRepr):
10171020
style = attr.ib(type="_TracebackStyle")
10181021

10191022
def _write_entry_lines(self, tw: TerminalWriter) -> None:
1020-
"""Writes the source code portions of a list of traceback entries with syntax highlighting.
1023+
"""Write the source code portions of a list of traceback entries with syntax highlighting.
10211024
10221025
Usually entries are lines like these:
10231026
@@ -1099,8 +1102,8 @@ class ReprFileLocation(TerminalRepr):
10991102
message = attr.ib(type=str)
11001103

11011104
def toterminal(self, tw: TerminalWriter) -> None:
1102-
# filename and lineno output for each entry,
1103-
# using an output format that most editors understand
1105+
# Filename and lineno output for each entry, using an output format
1106+
# that most editors understand.
11041107
msg = self.message
11051108
i = msg.find("\n")
11061109
if i != -1:
@@ -1175,10 +1178,10 @@ def getfslineno(obj: object) -> Tuple[Union[str, py.path.local], int]:
11751178
return code.path, code.firstlineno
11761179

11771180

1178-
# relative paths that we use to filter traceback entries from appearing to the user;
1179-
# see filter_traceback
1181+
# Relative paths that we use to filter traceback entries from appearing to the user;
1182+
# see filter_traceback.
11801183
# note: if we need to add more paths than what we have now we should probably use a list
1181-
# for better maintenance
1184+
# for better maintenance.
11821185

11831186
_PLUGGY_DIR = py.path.local(pluggy.__file__.rstrip("oc"))
11841187
# pluggy is either a package or a single module depending on the version
@@ -1197,14 +1200,14 @@ def filter_traceback(entry: TracebackEntry) -> bool:
11971200
* internal traceback from pytest or its internal libraries, py and pluggy.
11981201
"""
11991202
# entry.path might sometimes return a str object when the entry
1200-
# points to dynamically generated code
1201-
# see https://bitbucket.org/pytest-dev/py/issues/71
1203+
# points to dynamically generated code.
1204+
# See https://bitbucket.org/pytest-dev/py/issues/71.
12021205
raw_filename = entry.frame.code.raw.co_filename
12031206
is_generated = "<" in raw_filename and ">" in raw_filename
12041207
if is_generated:
12051208
return False
12061209
# entry.path might point to a non-existing file, in which case it will
1207-
# also return a str object. see #1133
1210+
# also return a str object. See #1133.
12081211
p = py.path.local(entry.path)
12091212
return (
12101213
not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR)

0 commit comments

Comments
 (0)