Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1445,8 +1445,18 @@ this API may be passed as the ``action`` parameter to
>>> parser.parse_args(['--no-foo'])
Namespace(foo=False)

Single-dash long options are also supported.
For example, negative option ``-nofoo`` is automatically added for
positive option ``-foo``.
But no additional options are added for short options such as ``-f``.

.. versionadded:: 3.9

.. versionchanged:: next
Added support for single-dash options.

Added support for alternate prefix_chars_.


The parse_args() method
-----------------------
Expand Down
10 changes: 8 additions & 2 deletions Doc/library/gc.rst
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,16 @@ The :mod:`gc` module provides the following functions:
to be uncollectable (and were therefore moved to the :data:`garbage`
list) inside this generation;

* ``candidates`` is the total number of objects in this generation which were
considered for collection and traversed;

* ``duration`` is the total time in seconds spent in collections for this
generation.

.. versionadded:: 3.4

.. versionchanged:: next
Add ``duration``.
Add ``duration`` and ``candidates``.


.. function:: set_threshold(threshold0, [threshold1, [threshold2]])
Expand Down Expand Up @@ -319,6 +322,9 @@ values but should not rebind them):
"uncollectable": When *phase* is "stop", the number of objects
that could not be collected and were put in :data:`garbage`.

"candidates": When *phase* is "stop", the total number of objects in this
generation which were considered for collection and traversed.

"duration": When *phase* is "stop", the time in seconds spent in the
collection.

Expand All @@ -335,7 +341,7 @@ values but should not rebind them):
.. versionadded:: 3.3

.. versionchanged:: next
Add "duration".
Add "duration" and "candidates".


The following constants are provided for use with :func:`set_debug`:
Expand Down
11 changes: 6 additions & 5 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4755,11 +4755,12 @@ other sequence-like behavior.

There are currently two built-in set types, :class:`set` and :class:`frozenset`.
The :class:`set` type is mutable --- the contents can be changed using methods
like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no
hash value and cannot be used as either a dictionary key or as an element of
another set. The :class:`frozenset` type is immutable and :term:`hashable` ---
its contents cannot be altered after it is created; it can therefore be used as
a dictionary key or as an element of another set.
like :meth:`add <frozenset.add>` and :meth:`remove <frozenset.add>`.
Since it is mutable, it has no hash value and cannot be used as
either a dictionary key or as an element of another set.
The :class:`frozenset` type is immutable and :term:`hashable` ---
its contents cannot be altered after it is created;
it can therefore be used as a dictionary key or as an element of another set.

Non-empty sets (not frozensets) can be created by placing a comma-separated list
of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the
Expand Down
50 changes: 25 additions & 25 deletions Doc/library/unittest.rst
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ run whether the test method succeeded or not.
Such a working environment for the testing code is called a
:dfn:`test fixture`. A new TestCase instance is created as a unique
test fixture used to execute each individual test method. Thus
:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`~TestCase.__init__`
:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`!TestCase.__init__`
will be called once per test.

It is recommended that you use TestCase implementations to group tests together
Expand Down Expand Up @@ -518,7 +518,7 @@ set-up and tear-down methods::
subclasses will make future test refactorings infinitely easier.

In some cases, the existing tests may have been written using the :mod:`doctest`
module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
module. If so, :mod:`doctest` provides a :class:`~doctest.DocTestSuite` class that can
automatically build :class:`unittest.TestSuite` instances from the existing
:mod:`doctest`\ -based tests.

Expand Down Expand Up @@ -1023,7 +1023,7 @@ Test cases
additional keyword argument *msg*.

The context manager will store the caught exception object in its
:attr:`exception` attribute. This can be useful if the intention
:attr:`!exception` attribute. This can be useful if the intention
is to perform additional checks on the exception raised::

with self.assertRaises(SomeException) as cm:
Expand All @@ -1036,7 +1036,7 @@ Test cases
Added the ability to use :meth:`assertRaises` as a context manager.

.. versionchanged:: 3.2
Added the :attr:`exception` attribute.
Added the :attr:`!exception` attribute.

.. versionchanged:: 3.3
Added the *msg* keyword argument when used as a context manager.
Expand Down Expand Up @@ -1089,8 +1089,8 @@ Test cases
additional keyword argument *msg*.

The context manager will store the caught warning object in its
:attr:`warning` attribute, and the source line which triggered the
warnings in the :attr:`filename` and :attr:`lineno` attributes.
:attr:`!warning` attribute, and the source line which triggered the
warnings in the :attr:`!filename` and :attr:`!lineno` attributes.
This can be useful if the intention is to perform additional checks
on the warning caught::

Expand Down Expand Up @@ -1437,7 +1437,7 @@ Test cases
that lists the differences between the sets. This method is used by
default when comparing sets or frozensets with :meth:`assertEqual`.

Fails if either of *first* or *second* does not have a :meth:`set.difference`
Fails if either of *first* or *second* does not have a :meth:`~frozenset.difference`
method.

.. versionadded:: 3.1
Expand Down Expand Up @@ -1645,7 +1645,7 @@ Test cases
.. method:: asyncSetUp()
:async:

Method called to prepare the test fixture. This is called after :meth:`setUp`.
Method called to prepare the test fixture. This is called after :meth:`TestCase.setUp`.
This is called immediately before calling the test method; other than
:exc:`AssertionError` or :exc:`SkipTest`, any exception raised by this method
will be considered an error rather than a test failure. The default implementation
Expand All @@ -1655,7 +1655,7 @@ Test cases
:async:

Method called immediately after the test method has been called and the
result recorded. This is called before :meth:`tearDown`. This is called even if
result recorded. This is called before :meth:`~TestCase.tearDown`. This is called even if
the test method raised an exception, so the implementation in subclasses may need
to be particularly careful about checking internal state. Any exception, other than
:exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
Expand Down Expand Up @@ -1684,7 +1684,7 @@ Test cases
Sets up a new event loop to run the test, collecting the result into
the :class:`TestResult` object passed as *result*. If *result* is
omitted or ``None``, a temporary result object is created (by calling
the :meth:`defaultTestResult` method) and used. The result object is
the :meth:`~TestCase.defaultTestResult` method) and used. The result object is
returned to :meth:`run`'s caller. At the end of the test all the tasks
in the event loop are cancelled.

Expand Down Expand Up @@ -1805,7 +1805,7 @@ Grouping tests
returned by repeated iterations before :meth:`TestSuite.run` must be the
same for each call iteration. After :meth:`TestSuite.run`, callers should
not rely on the tests returned by this method unless the caller uses a
subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
subclass that overrides :meth:`!TestSuite._removeTestAtIndex` to preserve
test references.

.. versionchanged:: 3.2
Expand All @@ -1816,10 +1816,10 @@ Grouping tests
.. versionchanged:: 3.4
In earlier versions the :class:`TestSuite` held references to each
:class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
that behavior by overriding :meth:`!TestSuite._removeTestAtIndex`.

In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
is invoked by a :class:`TestRunner` rather than by the end-user test harness.
is invoked by a :class:`!TestRunner` rather than by the end-user test harness.


Loading and running tests
Expand Down Expand Up @@ -1853,12 +1853,12 @@ Loading and running tests
.. method:: loadTestsFromTestCase(testCaseClass)

Return a suite of all test cases contained in the :class:`TestCase`\ -derived
:class:`testCaseClass`.
:class:`!testCaseClass`.

A test case instance is created for each method named by
:meth:`getTestCaseNames`. By default these are the method names
beginning with ``test``. If :meth:`getTestCaseNames` returns no
methods, but the :meth:`runTest` method is implemented, a single test
methods, but the :meth:`!runTest` method is implemented, a single test
case is created for that method instead.


Expand Down Expand Up @@ -1905,13 +1905,13 @@ Loading and running tests
case class will be picked up as "a test method within a test case class",
rather than "a callable object".

For example, if you have a module :mod:`SampleTests` containing a
:class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
For example, if you have a module :mod:`!SampleTests` containing a
:class:`TestCase`\ -derived class :class:`!SampleTestCase` with three test
methods (:meth:`!test_one`, :meth:`!test_two`, and :meth:`!test_three`), the
specifier ``'SampleTests.SampleTestCase'`` would cause this method to
return a suite which will run all three test methods. Using the specifier
``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
suite which will run only the :meth:`test_two` test method. The specifier
suite which will run only the :meth:`!test_two` test method. The specifier
can refer to modules and packages which have not been imported; they will
be imported as a side-effect.

Expand Down Expand Up @@ -2058,7 +2058,7 @@ Loading and running tests
Testing frameworks built on top of :mod:`unittest` may want access to the
:class:`TestResult` object generated by running a set of tests for reporting
purposes; a :class:`TestResult` instance is returned by the
:meth:`TestRunner.run` method for this purpose.
:meth:`!TestRunner.run` method for this purpose.

:class:`TestResult` instances have the following attributes that will be of
interest when inspecting the results of running a set of tests:
Expand Down Expand Up @@ -2144,12 +2144,12 @@ Loading and running tests

This method can be called to signal that the set of tests being run should
be aborted by setting the :attr:`shouldStop` attribute to ``True``.
:class:`TestRunner` objects should respect this flag and return without
:class:`!TestRunner` objects should respect this flag and return without
running any additional tests.

For example, this feature is used by the :class:`TextTestRunner` class to
stop the test framework when the user signals an interrupt from the
keyboard. Interactive tools which provide :class:`TestRunner`
keyboard. Interactive tools which provide :class:`!TestRunner`
implementations can use this in a similar manner.

The following methods of the :class:`TestResult` class are used to maintain
Expand Down Expand Up @@ -2469,9 +2469,9 @@ Class and Module Fixtures
-------------------------

Class and module level fixtures are implemented in :class:`TestSuite`. When
the test suite encounters a test from a new class then :meth:`tearDownClass`
from the previous class (if there is one) is called, followed by
:meth:`setUpClass` from the new class.
the test suite encounters a test from a new class then
:meth:`~TestCase.tearDownClass` from the previous class (if there is one)
is called, followed by :meth:`~TestCase.setUpClass` from the new class.

Similarly if a test is from a different module from the previous test then
``tearDownModule`` from the previous module is run, followed by
Expand Down
2 changes: 0 additions & 2 deletions Doc/tools/.nitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,12 @@ Doc/library/pyexpat.rst
Doc/library/select.rst
Doc/library/socket.rst
Doc/library/ssl.rst
Doc/library/stdtypes.rst
Doc/library/termios.rst
Doc/library/test.rst
Doc/library/tkinter.rst
Doc/library/tkinter.scrolledtext.rst
Doc/library/tkinter.ttk.rst
Doc/library/unittest.mock.rst
Doc/library/unittest.rst
Doc/library/urllib.parse.rst
Doc/library/urllib.request.rst
Doc/library/wsgiref.rst
Expand Down
4 changes: 4 additions & 0 deletions Doc/whatsnew/3.15.rst
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,10 @@ Improved modules
argparse
--------

* The :class:`~argparse.BooleanOptionalAction` action supports now single-dash
long options and alternate prefix characters.
(Contributed by Serhiy Storchaka in :gh:`138525`.)

* Changed the *suggest_on_error* parameter of :class:`argparse.ArgumentParser` to
default to ``True``. This enables suggestions for mistyped arguments by default.
(Contributed by Jakob Schluse in :gh:`140450`.)
Expand Down
4 changes: 4 additions & 0 deletions Include/internal/pycore_interp_structs.h
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ struct gc_collection_stats {
Py_ssize_t collected;
/* total number of uncollectable objects (put into gc.garbage) */
Py_ssize_t uncollectable;
// Total number of objects considered for collection and traversed:
Py_ssize_t candidates;
// Duration of the collection in seconds:
double duration;
};
Expand All @@ -191,6 +193,8 @@ struct gc_generation_stats {
Py_ssize_t collected;
/* total number of uncollectable objects (put into gc.garbage) */
Py_ssize_t uncollectable;
// Total number of objects considered for collection and traversed:
Py_ssize_t candidates;
// Duration of the collection in seconds:
double duration;
};
Expand Down
20 changes: 16 additions & 4 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,15 +932,26 @@ def __init__(self,
deprecated=False):

_option_strings = []
neg_option_strings = []
for option_string in option_strings:
_option_strings.append(option_string)

if option_string.startswith('--'):
if option_string.startswith('--no-'):
if len(option_string) > 2 and option_string[0] == option_string[1]:
# two-dash long option: '--foo' -> '--no-foo'
if option_string.startswith('no-', 2):
raise ValueError(f'invalid option name {option_string!r} '
f'for BooleanOptionalAction')
option_string = '--no-' + option_string[2:]
option_string = option_string[:2] + 'no-' + option_string[2:]
_option_strings.append(option_string)
neg_option_strings.append(option_string)
elif len(option_string) > 2 and option_string[0] != option_string[1]:
# single-dash long option: '-foo' -> '-nofoo'
if option_string.startswith('no', 1):
raise ValueError(f'invalid option name {option_string!r} '
f'for BooleanOptionalAction')
option_string = option_string[:1] + 'no' + option_string[1:]
_option_strings.append(option_string)
neg_option_strings.append(option_string)

super().__init__(
option_strings=_option_strings,
Expand All @@ -950,11 +961,12 @@ def __init__(self,
required=required,
help=help,
deprecated=deprecated)
self.neg_option_strings = neg_option_strings


def __call__(self, parser, namespace, values, option_string=None):
if option_string in self.option_strings:
setattr(namespace, self.dest, not option_string.startswith('--no-'))
setattr(namespace, self.dest, option_string not in self.neg_option_strings)

def format_usage(self):
return ' | '.join(self.option_strings)
Expand Down
1 change: 1 addition & 0 deletions Lib/multiprocessing/forkserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ def sigchld_handler(*_unused):
len(fds)))
child_r, child_w, *fds = fds
s.close()
util._flush_std_streams()
pid = os.fork()
if pid == 0:
# Child
Expand Down
4 changes: 2 additions & 2 deletions Lib/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def libc_ver(executable=None, lib='', version='', chunksize=16384):
| (GLIBC_([0-9.]+))
| (libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)
| (musl-([0-9.]+))
| (libc.musl(?:-\w+)?.so(?:\.(\d[0-9.]*))?)
| ((?:libc\.|ld-)musl(?:-\w+)?.so(?:\.(\d[0-9.]*))?)
""",
re.ASCII | re.VERBOSE)

Expand Down Expand Up @@ -236,7 +236,7 @@ def libc_ver(executable=None, lib='', version='', chunksize=16384):
elif V(glibcversion) > V(ver):
ver = glibcversion
elif so:
if lib != 'glibc':
if lib not in ('glibc', 'musl'):
lib = 'libc'
if soversion and (not ver or V(soversion) > V(ver)):
ver = soversion
Expand Down
Loading
Loading