Skip to content

Commit d3c42b7

Browse files
committed
Merge branch 'main' of https://github.com/python/cpython into more-arg-clinic
2 parents 02e17e3 + 796b26b commit d3c42b7

33 files changed

Lines changed: 446 additions & 167 deletions

‎Doc/library/argparse.rst‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2072,6 +2072,19 @@ Argument groups
20722072
is now deprecated.
20732073

20742074

2075+
.. class:: ArgumentGroup
2076+
2077+
The type of objects returned by :meth:`ArgumentParser.add_argument_group`.
2078+
Its :meth:`~ArgumentParser.add_argument` and
2079+
:meth:`~ArgumentParser.add_mutually_exclusive_group` methods work as on
2080+
:class:`ArgumentParser`. Use :meth:`~ArgumentParser.add_argument_group`
2081+
to create instances. Only the methods documented here are part of the
2082+
public API; other attributes and methods are implementation details.
2083+
2084+
.. versionadded:: next
2085+
The private ``_ArgumentGroup`` name remains as an alias.
2086+
2087+
20752088
Mutual exclusion
20762089
^^^^^^^^^^^^^^^^
20772090

@@ -2135,6 +2148,20 @@ Mutual exclusion
21352148
exposed through inheritance.
21362149

21372150

2151+
.. class:: MutuallyExclusiveGroup
2152+
2153+
The type of objects returned by
2154+
:meth:`ArgumentParser.add_mutually_exclusive_group`.
2155+
Its :meth:`~ArgumentParser.add_argument` method works as on
2156+
:class:`ArgumentParser`. Use
2157+
:meth:`~ArgumentParser.add_mutually_exclusive_group` to create instances.
2158+
Only the ``add_argument`` method documented here is part of the public API;
2159+
other attributes and methods are implementation details.
2160+
2161+
.. versionadded:: next
2162+
The private ``_MutuallyExclusiveGroup`` name remains as an alias.
2163+
2164+
21382165
Parser defaults
21392166
^^^^^^^^^^^^^^^
21402167

‎Doc/library/ctypes.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1563,7 +1563,7 @@ way is to instantiate :py:class:`CDLL` or one of its subclasses:
15631563
On non-Windows systems, *name* can be ``None``. In this case,
15641564
:c:func:`!dlopen` is called with ``NULL``, which opens the main program
15651565
as a "library".
1566-
(Some systems do the same is *name* is empty; ``None``/``NULL`` is more
1566+
(Some systems do the same if *name* is empty; ``None``/``NULL`` is more
15671567
portable.)
15681568

15691569
.. admonition:: CPython implementation detail

‎Doc/whatsnew/3.16.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,16 @@ New modules
126126
Improved modules
127127
================
128128

129+
argparse
130+
--------
131+
132+
* :class:`~argparse.ArgumentGroup` and
133+
:class:`~argparse.MutuallyExclusiveGroup`, the types returned by
134+
:meth:`~argparse.ArgumentParser.add_argument_group` and
135+
:meth:`~argparse.ArgumentParser.add_mutually_exclusive_group`, are now
136+
public. The ``_``-prefixed names remain as aliases.
137+
(Contributed by Bernát Gábor in :gh:`144812`.)
138+
129139
asyncio
130140
-------
131141

‎Lib/argparse.py‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@
6767
__all__ = [
6868
'ArgumentParser',
6969
'ArgumentError',
70+
'ArgumentGroup',
7071
'ArgumentTypeError',
7172
'BooleanOptionalAction',
7273
'FileType',
@@ -75,6 +76,7 @@
7576
'RawDescriptionHelpFormatter',
7677
'RawTextHelpFormatter',
7778
'MetavarTypeHelpFormatter',
79+
'MutuallyExclusiveGroup',
7880
'Namespace',
7981
'Action',
8082
'ONE_OR_MORE',
@@ -1699,12 +1701,12 @@ def add_argument(self, *args, **kwargs):
16991701
return self._add_action(action)
17001702

17011703
def add_argument_group(self, *args, **kwargs):
1702-
group = _ArgumentGroup(self, *args, **kwargs)
1704+
group = ArgumentGroup(self, *args, **kwargs)
17031705
self._action_groups.append(group)
17041706
return group
17051707

17061708
def add_mutually_exclusive_group(self, **kwargs):
1707-
group = _MutuallyExclusiveGroup(self, **kwargs)
1709+
group = MutuallyExclusiveGroup(self, **kwargs)
17081710
self._mutually_exclusive_groups.append(group)
17091711
return group
17101712

@@ -1892,7 +1894,7 @@ def _check_help(self, action):
18921894
raise ValueError('badly formed help string') from exc
18931895

18941896

1895-
class _ArgumentGroup(_ActionsContainer):
1897+
class ArgumentGroup(_ActionsContainer):
18961898

18971899
def __init__(self, container, title=None, description=None, **kwargs):
18981900
if 'prefix_chars' in kwargs:
@@ -1907,7 +1909,7 @@ def __init__(self, container, title=None, description=None, **kwargs):
19071909
update('conflict_handler', container.conflict_handler)
19081910
update('prefix_chars', container.prefix_chars)
19091911
update('argument_default', container.argument_default)
1910-
super_init = super(_ArgumentGroup, self).__init__
1912+
super_init = super(ArgumentGroup, self).__init__
19111913
super_init(description=description, **kwargs)
19121914

19131915
# group attributes
@@ -1924,21 +1926,21 @@ def __init__(self, container, title=None, description=None, **kwargs):
19241926
self._mutually_exclusive_groups = container._mutually_exclusive_groups
19251927

19261928
def _add_action(self, action):
1927-
action = super(_ArgumentGroup, self)._add_action(action)
1929+
action = super(ArgumentGroup, self)._add_action(action)
19281930
self._group_actions.append(action)
19291931
return action
19301932

19311933
def _remove_action(self, action):
1932-
super(_ArgumentGroup, self)._remove_action(action)
1934+
super(ArgumentGroup, self)._remove_action(action)
19331935
self._group_actions.remove(action)
19341936

19351937
def add_argument_group(self, *args, **kwargs):
19361938
raise ValueError('argument groups cannot be nested')
19371939

1938-
class _MutuallyExclusiveGroup(_ArgumentGroup):
1940+
class MutuallyExclusiveGroup(ArgumentGroup):
19391941

19401942
def __init__(self, container, required=False):
1941-
super(_MutuallyExclusiveGroup, self).__init__(container)
1943+
super(MutuallyExclusiveGroup, self).__init__(container)
19421944
self.required = required
19431945
self._container = container
19441946

@@ -1957,6 +1959,10 @@ def _remove_action(self, action):
19571959
def add_mutually_exclusive_group(self, **kwargs):
19581960
raise ValueError('mutually exclusive groups cannot be nested')
19591961

1962+
# Kept for code that imports the pre-3.16 private names.
1963+
_ArgumentGroup = ArgumentGroup
1964+
_MutuallyExclusiveGroup = MutuallyExclusiveGroup
1965+
19601966
def _prog_name(prog=None):
19611967
if prog is not None:
19621968
return prog

‎Lib/hmac.py‎

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,27 @@ def digest_wrapper(d=b''):
4949
return digest_wrapper
5050

5151

52+
def _select_blocksize(obj, default, stacklevel=3):
53+
if hasattr(obj, 'block_size'):
54+
blocksize = obj.block_size
55+
if blocksize < 16:
56+
import warnings
57+
58+
warnings.warn(f"block_size of {blocksize} seems too small; "
59+
f"using our default of {default}.",
60+
RuntimeWarning, stacklevel=stacklevel)
61+
blocksize = default
62+
else:
63+
import warnings
64+
65+
warnings.warn("No block_size attribute on given digest object; "
66+
f"Assuming {default}.",
67+
RuntimeWarning, stacklevel=stacklevel)
68+
blocksize = default
69+
return blocksize
70+
71+
72+
5273
class HMAC:
5374
"""RFC 2104 HMAC class. Also complies with RFC 4231.
5475
@@ -116,8 +137,6 @@ def _init_builtin_hmac(self, key, msg, digestmod):
116137
self.block_size = self._hmac.block_size
117138

118139
def _init_old(self, key, msg, digestmod):
119-
import warnings
120-
121140
digest_cons = _get_digest_constructor(digestmod)
122141
if _is_shake_constructor(digest_cons):
123142
raise ValueError(f"unsupported hash algorithm {digestmod}")
@@ -127,19 +146,7 @@ def _init_old(self, key, msg, digestmod):
127146
self._inner = digest_cons()
128147
self.digest_size = self._inner.digest_size
129148

130-
if hasattr(self._inner, 'block_size'):
131-
blocksize = self._inner.block_size
132-
if blocksize < 16:
133-
warnings.warn(f"block_size of {blocksize} seems too small; "
134-
f"using our default of {self.blocksize}.",
135-
RuntimeWarning, 2)
136-
blocksize = self.blocksize # pragma: no cover
137-
else:
138-
warnings.warn("No block_size attribute on given digest object; "
139-
f"Assuming {self.blocksize}.",
140-
RuntimeWarning, 2)
141-
blocksize = self.blocksize # pragma: no cover
142-
149+
blocksize = _select_blocksize(self._inner, self.blocksize)
143150
if len(key) > blocksize:
144151
key = digest_cons(key).digest()
145152

@@ -275,7 +282,7 @@ def _compute_digest_fallback(key, msg, digest):
275282
raise ValueError(f"unsupported hash algorithm {digest}")
276283
inner = digest_cons()
277284
outer = digest_cons()
278-
blocksize = getattr(inner, 'block_size', 64)
285+
blocksize = _select_blocksize(inner, HMAC.blocksize)
279286
if len(key) > blocksize:
280287
key = digest_cons(key).digest()
281288
key = key.ljust(blocksize, b'\0')

‎Lib/test/libregrtest/logger.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,12 @@ def log(self, line: str = '') -> None:
2929
if self.get_mem_usage is not None:
3030
mem = self.get_mem_usage()
3131
if mem:
32-
mib = mem / (1024*1024)
33-
if mib >= 1024:
34-
line = f"mem: {mib / 1024:.1f} GiB {line}"
35-
else:
36-
line = f"mem: {mib:.1f} MiB {line}"
32+
qty = mem / (1024*1024)
33+
unit = 'MiB'
34+
if qty >= 1024:
35+
qty = qty / 1024
36+
unit = 'GiB'
37+
line = f"mem: {qty:6.1f} {unit} {line}"
3738

3839
# Add the system load prefix: "load avg: 1.80 "
3940
load_avg = self.get_load_avg()

‎Lib/test/test_argparse.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3246,6 +3246,20 @@ def test_nested_argument_group(self):
32463246
'argument groups cannot be nested',
32473247
g.add_argument_group)
32483248

3249+
def test_group_types(self):
3250+
parser = argparse.ArgumentParser()
3251+
group = parser.add_argument_group()
3252+
self.assertIs(type(group), argparse.ArgumentGroup)
3253+
self.assertIs(type(parser.add_mutually_exclusive_group()),
3254+
argparse.MutuallyExclusiveGroup)
3255+
self.assertIs(type(group.add_mutually_exclusive_group()),
3256+
argparse.MutuallyExclusiveGroup)
3257+
3258+
def test_private_aliases(self):
3259+
self.assertIs(argparse._ArgumentGroup, argparse.ArgumentGroup)
3260+
self.assertIs(argparse._MutuallyExclusiveGroup,
3261+
argparse.MutuallyExclusiveGroup)
3262+
32493263
# ===================
32503264
# Parent parser tests
32513265
# ===================

‎Lib/test/test_hmac.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1501,17 +1501,36 @@ def update(self, v):
15011501
self._x.update(v)
15021502
def digest(self):
15031503
return self._x.digest()
1504+
def copy(self):
1505+
h = MockCrazyHash()
1506+
h._x = self._x.copy()
1507+
return h
15041508

15051509
with warnings.catch_warnings():
15061510
warnings.simplefilter('error', RuntimeWarning)
15071511
with self.assertRaises(RuntimeWarning):
15081512
hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
15091513
self.fail('Expected warning about missing block_size')
1514+
with self.assertRaises(RuntimeWarning):
1515+
hmac.digest(b'a', b'b', MockCrazyHash)
1516+
self.fail('Expected warning about missing block_size')
15101517

15111518
MockCrazyHash.block_size = 1
15121519
with self.assertRaises(RuntimeWarning):
15131520
hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
15141521
self.fail('Expected warning about small block_size')
1522+
with self.assertRaises(RuntimeWarning):
1523+
hmac.digest(b'a', b'b', MockCrazyHash)
1524+
self.fail('Expected warning about small block_size')
1525+
1526+
# gh-155428: hmac.HMAC() and hmac.digest() must both
1527+
# fall back to the default block size (64 for SHA-256).
1528+
expect = hmac.digest(b'a', b'b', 'sha256')
1529+
with warnings.catch_warnings():
1530+
warnings.simplefilter('ignore', RuntimeWarning)
1531+
h = hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
1532+
self.assertEqual(h.digest(), expect)
1533+
self.assertEqual(hmac.digest(b'a', b'b', MockCrazyHash), expect)
15151534

15161535
@hashlib_helper.requires_hashdigest('sha256')
15171536
def test_with_fallback(self):

‎Lib/test/test_regrtest.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
LOG_PREFIX = (
4949
r'[0-9]+:[0-9]+:[0-9]+ '
5050
r'(?:load avg: [0-9]+\.[0-9]{2} )?'
51-
r'(?:mem: [0-9]+\.[0-9] (?:MiB|GiB) )?'
51+
r'(?:mem: +[0-9]+\.[0-9] (?:MiB|GiB) )?'
5252
)
5353
RESULT_REGEX = (
5454
'passed',

‎Lib/test/test_zoneinfo/test_zoneinfo.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1492,6 +1492,33 @@ def _add():
14921492
(datetime(2020, 12, 31, 23, 59, 59, 999999), AAA, NORMAL),
14931493
)
14941494

1495+
@call
1496+
def _add():
1497+
# Julian days 58, 59 and 60 always mean February 27, February 28
1498+
# and March 1, including in leap years.
1499+
AAA = ZoneOffset("AAA", ZERO)
1500+
BBB = ZoneOffset("BBB", ONE_H, ONE_H)
1501+
1502+
for start, end, start_date, end_date in (
1503+
(58, 59, (2, 27), (2, 28)),
1504+
(59, 60, (2, 28), (3, 1)),
1505+
):
1506+
tzstr = f"AAA0BBB,J{start}/12,J{end}/12"
1507+
cases[tzstr] = []
1508+
for year in (2019, 2020, 2000, 2100):
1509+
start_dt = datetime(year, *start_date, 12)
1510+
end_dt = datetime(year, *end_date, 12)
1511+
cases[tzstr].extend((
1512+
(start_dt - timedelta(seconds=1), AAA, NORMAL),
1513+
(start_dt, AAA, GAP),
1514+
(start_dt.replace(fold=1), BBB, GAP),
1515+
(start_dt + ONE_H, BBB, NORMAL),
1516+
(end_dt - ONE_H - timedelta(seconds=1), BBB, NORMAL),
1517+
(end_dt - ONE_H, BBB, FOLD),
1518+
((end_dt - ONE_H).replace(fold=1), AAA, FOLD),
1519+
(end_dt, AAA, NORMAL),
1520+
))
1521+
14951522
@call
14961523
def _add():
14971524
# Taken from America/Godthab, this rule has a transition on the

0 commit comments

Comments
 (0)