Skip to content

Commit 2085bd0

Browse files
bpo-37116: Use PEP 570 syntax for positional-only parameters. (GH-13700)
1 parent 4a68650 commit 2085bd0

34 files changed

+126
-261
lines changed

Doc/library/collections.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1140,7 +1140,7 @@ variants of :func:`functools.lru_cache`::
11401140
class LRU(OrderedDict):
11411141
'Limit size, evicting the least recently looked-up key when full'
11421142

1143-
def __init__(self, maxsize=128, *args, **kwds):
1143+
def __init__(self, maxsize=128, /, *args, **kwds):
11441144
self.maxsize = maxsize
11451145
super().__init__(*args, **kwds)
11461146

Doc/library/contextlib.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -637,7 +637,7 @@ even further by means of a small helper class::
637637
from contextlib import ExitStack
638638

639639
class Callback(ExitStack):
640-
def __init__(self, callback, *args, **kwds):
640+
def __init__(self, callback, /, *args, **kwds):
641641
super(Callback, self).__init__()
642642
self.callback(callback, *args, **kwds)
643643

Doc/library/email.headerregistry.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ headers.
107107
method if it wishes to set additional attributes beyond those provided by
108108
``BaseHeader`` itself. Such an ``init`` method should look like this::
109109

110-
def init(self, *args, **kw):
110+
def init(self, /, *args, **kw):
111111
self._myattr = kw.pop('myattr')
112112
super().init(*args, **kw)
113113

Doc/library/functools.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ The :mod:`functools` module defines the following functions:
221221
Returning NotImplemented from the underlying comparison function for
222222
unrecognised types is now supported.
223223

224-
.. function:: partial(func, *args, **keywords)
224+
.. function:: partial(func, /, *args, **keywords)
225225

226226
Return a new :ref:`partial object<partial-objects>` which when called
227227
will behave like *func* called with the positional arguments *args*
@@ -230,7 +230,7 @@ The :mod:`functools` module defines the following functions:
230230
supplied, they extend and override *keywords*.
231231
Roughly equivalent to::
232232

233-
def partial(func, *args, **keywords):
233+
def partial(func, /, *args, **keywords):
234234
def newfunc(*fargs, **fkeywords):
235235
newkeywords = {**keywords, **fkeywords}
236236
return func(*args, *fargs, **newkeywords)

Doc/library/inspect.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1022,7 +1022,7 @@ Classes and functions
10221022
metatype is in use, cls will be the first element of the tuple.
10231023

10241024

1025-
.. function:: getcallargs(func, *args, **kwds)
1025+
.. function:: getcallargs(func, /, *args, **kwds)
10261026

10271027
Bind the *args* and *kwds* to the argument names of the Python function or
10281028
method *func*, as if it was called with them. For bound methods, bind also the

Doc/library/operator.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ expect a function argument.
339339
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
340340

341341

342-
.. function:: methodcaller(name[, args...])
342+
.. function:: methodcaller(name, /, *args, **kwargs)
343343

344344
Return a callable object that calls the method *name* on its operand. If
345345
additional arguments and/or keyword arguments are given, they will be given
@@ -352,7 +352,7 @@ expect a function argument.
352352

353353
Equivalent to::
354354

355-
def methodcaller(name, *args, **kwargs):
355+
def methodcaller(name, /, *args, **kwargs):
356356
def caller(obj):
357357
return getattr(obj, name)(*args, **kwargs)
358358
return caller

Doc/library/string.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ implementation as the built-in :meth:`~str.format` method.
8888

8989
The :class:`Formatter` class has the following public methods:
9090

91-
.. method:: format(format_string, *args, **kwargs)
91+
.. method:: format(format_string, /, *args, **kwargs)
9292

9393
The primary API method. It takes a format string and
9494
an arbitrary set of positional and keyword arguments.
@@ -720,7 +720,7 @@ these rules. The methods of :class:`Template` are:
720720
The constructor takes a single argument which is the template string.
721721

722722

723-
.. method:: substitute(mapping, **kwds)
723+
.. method:: substitute(mapping={}, /, **kwds)
724724

725725
Performs the template substitution, returning a new string. *mapping* is
726726
any dictionary-like object with keys that match the placeholders in the
@@ -729,7 +729,7 @@ these rules. The methods of :class:`Template` are:
729729
and there are duplicates, the placeholders from *kwds* take precedence.
730730

731731

732-
.. method:: safe_substitute(mapping, **kwds)
732+
.. method:: safe_substitute(mapping={}, /, **kwds)
733733

734734
Like :meth:`substitute`, except that if placeholders are missing from
735735
*mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the

Doc/library/types.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ Additional Utility Classes and Functions
327327
The type is roughly equivalent to the following code::
328328

329329
class SimpleNamespace:
330-
def __init__(self, **kwargs):
330+
def __init__(self, /, **kwargs):
331331
self.__dict__.update(kwargs)
332332

333333
def __repr__(self):

Doc/library/unittest.mock-examples.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -848,7 +848,7 @@ Here's an example implementation:
848848

849849
>>> from copy import deepcopy
850850
>>> class CopyingMock(MagicMock):
851-
... def __call__(self, *args, **kwargs):
851+
... def __call__(self, /, *args, **kwargs):
852852
... args = deepcopy(args)
853853
... kwargs = deepcopy(kwargs)
854854
... return super(CopyingMock, self).__call__(*args, **kwargs)
@@ -1042,7 +1042,7 @@ that it takes arbitrary keyword arguments (``**kwargs``) which are then passed
10421042
onto the mock constructor:
10431043

10441044
>>> class Subclass(MagicMock):
1045-
... def _get_child_mock(self, **kwargs):
1045+
... def _get_child_mock(self, /, **kwargs):
10461046
... return MagicMock(**kwargs)
10471047
...
10481048
>>> mymock = Subclass()

Doc/library/unittest.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1456,7 +1456,7 @@ Test cases
14561456

14571457
.. versionadded:: 3.1
14581458

1459-
.. classmethod:: addClassCleanup(function, *args, **kwargs)
1459+
.. classmethod:: addClassCleanup(function, /, *args, **kwargs)
14601460

14611461
Add a function to be called after :meth:`tearDownClass` to cleanup
14621462
resources used during the test class. Functions will be called in reverse
@@ -2313,7 +2313,7 @@ To add cleanup code that must be run even in the case of an exception, use
23132313
``addModuleCleanup``:
23142314

23152315

2316-
.. function:: addModuleCleanup(function, *args, **kwargs)
2316+
.. function:: addModuleCleanup(function, /, *args, **kwargs)
23172317

23182318
Add a function to be called after :func:`tearDownModule` to cleanup
23192319
resources used during the test class. Functions will be called in reverse

Doc/library/weakref.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ the referent is accessed::
396396
import weakref
397397

398398
class ExtendedRef(weakref.ref):
399-
def __init__(self, ob, callback=None, **annotations):
399+
def __init__(self, ob, callback=None, /, **annotations):
400400
super(ExtendedRef, self).__init__(ob, callback)
401401
self.__counter = 0
402402
for k, v in annotations.items():

Doc/whatsnew/3.8.rst

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -941,8 +941,7 @@ Deprecated
941941
:meth:`profile.Profile.runcall`, :meth:`cProfile.Profile.runcall`,
942942
:meth:`bdb.Bdb.runcall`, :meth:`trace.Trace.runfunc` and
943943
:func:`curses.wrapper`.
944-
- *function* in :func:`unittest.addModuleCleanup` and
945-
:meth:`unittest.TestCase.addCleanup`.
944+
- *function* in :meth:`unittest.TestCase.addCleanup`.
946945
- *fn* in the :meth:`~concurrent.futures.Executor.submit` method of
947946
:class:`concurrent.futures.ThreadPoolExecutor` and
948947
:class:`concurrent.futures.ProcessPoolExecutor`.

Lib/_collections_abc.py

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -821,30 +821,21 @@ def clear(self):
821821
except KeyError:
822822
pass
823823

824-
def update(*args, **kwds):
824+
def update(self, other=(), /, **kwds):
825825
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
826826
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
827827
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
828828
In either case, this is followed by: for k, v in F.items(): D[k] = v
829829
'''
830-
if not args:
831-
raise TypeError("descriptor 'update' of 'MutableMapping' object "
832-
"needs an argument")
833-
self, *args = args
834-
if len(args) > 1:
835-
raise TypeError('update expected at most 1 arguments, got %d' %
836-
len(args))
837-
if args:
838-
other = args[0]
839-
if isinstance(other, Mapping):
840-
for key in other:
841-
self[key] = other[key]
842-
elif hasattr(other, "keys"):
843-
for key in other.keys():
844-
self[key] = other[key]
845-
else:
846-
for key, value in other:
847-
self[key] = value
830+
if isinstance(other, Mapping):
831+
for key in other:
832+
self[key] = other[key]
833+
elif hasattr(other, "keys"):
834+
for key in other.keys():
835+
self[key] = other[key]
836+
else:
837+
for key, value in other:
838+
self[key] = value
848839
for key, value in kwds.items():
849840
self[key] = value
850841

Lib/_py_abc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class ABCMeta(type):
3232
# external code.
3333
_abc_invalidation_counter = 0
3434

35-
def __new__(mcls, name, bases, namespace, **kwargs):
35+
def __new__(mcls, name, bases, namespace, /, **kwargs):
3636
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
3737
# Compute set of abstract method names
3838
abstracts = {name

Lib/_threading_local.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
5757
>>> class MyLocal(local):
5858
... number = 2
59-
... def __init__(self, **kw):
59+
... def __init__(self, /, **kw):
6060
... self.__dict__.update(kw)
6161
... def squared(self):
6262
... return self.number ** 2
@@ -204,7 +204,7 @@ def _patch(self):
204204
class local:
205205
__slots__ = '_local__impl', '__dict__'
206206

207-
def __new__(cls, *args, **kw):
207+
def __new__(cls, /, *args, **kw):
208208
if (args or kw) and (cls.__init__ is object.__init__):
209209
raise TypeError("Initialization arguments are not supported")
210210
self = object.__new__(cls)

Lib/collections/__init__.py

Lines changed: 10 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -93,24 +93,18 @@ class OrderedDict(dict):
9393
# Individual links are kept alive by the hard reference in self.__map.
9494
# Those hard references disappear when a key is deleted from an OrderedDict.
9595

96-
def __init__(*args, **kwds):
96+
def __init__(self, other=(), /, **kwds):
9797
'''Initialize an ordered dictionary. The signature is the same as
9898
regular dictionaries. Keyword argument order is preserved.
9999
'''
100-
if not args:
101-
raise TypeError("descriptor '__init__' of 'OrderedDict' object "
102-
"needs an argument")
103-
self, *args = args
104-
if len(args) > 1:
105-
raise TypeError('expected at most 1 arguments, got %d' % len(args))
106100
try:
107101
self.__root
108102
except AttributeError:
109103
self.__hardroot = _Link()
110104
self.__root = root = _proxy(self.__hardroot)
111105
root.prev = root.next = root
112106
self.__map = {}
113-
self.__update(*args, **kwds)
107+
self.__update(other, **kwds)
114108

115109
def __setitem__(self, key, value,
116110
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
@@ -413,8 +407,8 @@ def _make(cls, iterable):
413407
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
414408
'or iterable')
415409

416-
def _replace(_self, **kwds):
417-
result = _self._make(_map(kwds.pop, field_names, _self))
410+
def _replace(self, /, **kwds):
411+
result = self._make(_map(kwds.pop, field_names, self))
418412
if kwds:
419413
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
420414
return result
@@ -543,7 +537,7 @@ class Counter(dict):
543537
# http://code.activestate.com/recipes/259174/
544538
# Knuth, TAOCP Vol. II section 4.6.3
545539

546-
def __init__(*args, **kwds):
540+
def __init__(self, iterable=None, /, **kwds):
547541
'''Create a new, empty Counter object. And if given, count elements
548542
from an input iterable. Or, initialize the count from another mapping
549543
of elements to their counts.
@@ -554,14 +548,8 @@ def __init__(*args, **kwds):
554548
>>> c = Counter(a=4, b=2) # a new counter from keyword args
555549
556550
'''
557-
if not args:
558-
raise TypeError("descriptor '__init__' of 'Counter' object "
559-
"needs an argument")
560-
self, *args = args
561-
if len(args) > 1:
562-
raise TypeError('expected at most 1 arguments, got %d' % len(args))
563551
super(Counter, self).__init__()
564-
self.update(*args, **kwds)
552+
self.update(iterable, **kwds)
565553

566554
def __missing__(self, key):
567555
'The count of elements not in the Counter is zero.'
@@ -617,7 +605,7 @@ def fromkeys(cls, iterable, v=None):
617605
raise NotImplementedError(
618606
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
619607

620-
def update(*args, **kwds):
608+
def update(self, iterable=None, /, **kwds):
621609
'''Like dict.update() but add counts instead of replacing them.
622610
623611
Source can be an iterable, a dictionary, or another Counter instance.
@@ -637,13 +625,6 @@ def update(*args, **kwds):
637625
# contexts. Instead, we implement straight-addition. Both the inputs
638626
# and outputs are allowed to contain zero and negative counts.
639627

640-
if not args:
641-
raise TypeError("descriptor 'update' of 'Counter' object "
642-
"needs an argument")
643-
self, *args = args
644-
if len(args) > 1:
645-
raise TypeError('expected at most 1 arguments, got %d' % len(args))
646-
iterable = args[0] if args else None
647628
if iterable is not None:
648629
if isinstance(iterable, _collections_abc.Mapping):
649630
if self:
@@ -657,7 +638,7 @@ def update(*args, **kwds):
657638
if kwds:
658639
self.update(kwds)
659640

660-
def subtract(*args, **kwds):
641+
def subtract(self, iterable=None, /, **kwds):
661642
'''Like dict.update() but subtracts counts instead of replacing them.
662643
Counts can be reduced below zero. Both the inputs and outputs are
663644
allowed to contain zero and negative counts.
@@ -673,13 +654,6 @@ def subtract(*args, **kwds):
673654
-1
674655
675656
'''
676-
if not args:
677-
raise TypeError("descriptor 'subtract' of 'Counter' object "
678-
"needs an argument")
679-
self, *args = args
680-
if len(args) > 1:
681-
raise TypeError('expected at most 1 arguments, got %d' % len(args))
682-
iterable = args[0] if args else None
683657
if iterable is not None:
684658
self_get = self.get
685659
if isinstance(iterable, _collections_abc.Mapping):
@@ -1141,7 +1115,7 @@ def copy(self): return self.__class__(self)
11411115
def count(self, item): return self.data.count(item)
11421116
def index(self, item, *args): return self.data.index(item, *args)
11431117
def reverse(self): self.data.reverse()
1144-
def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
1118+
def sort(self, /, *args, **kwds): self.data.sort(*args, **kwds)
11451119
def extend(self, other):
11461120
if isinstance(other, UserList):
11471121
self.data.extend(other.data)
@@ -1240,7 +1214,7 @@ def find(self, sub, start=0, end=_sys.maxsize):
12401214
if isinstance(sub, UserString):
12411215
sub = sub.data
12421216
return self.data.find(sub, start, end)
1243-
def format(self, *args, **kwds):
1217+
def format(self, /, *args, **kwds):
12441218
return self.data.format(*args, **kwds)
12451219
def format_map(self, mapping):
12461220
return self.data.format_map(mapping)

Lib/contextlib.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -377,8 +377,7 @@ def _create_exit_wrapper(cm, cm_exit):
377377
return MethodType(cm_exit, cm)
378378

379379
@staticmethod
380-
def _create_cb_wrapper(*args, **kwds):
381-
callback, *args = args
380+
def _create_cb_wrapper(callback, /, *args, **kwds):
382381
def _exit_wrapper(exc_type, exc, tb):
383382
callback(*args, **kwds)
384383
return _exit_wrapper
@@ -553,8 +552,7 @@ def _create_async_exit_wrapper(cm, cm_exit):
553552
return MethodType(cm_exit, cm)
554553

555554
@staticmethod
556-
def _create_async_cb_wrapper(*args, **kwds):
557-
callback, *args = args
555+
def _create_async_cb_wrapper(callback, /, *args, **kwds):
558556
async def _exit_wrapper(exc_type, exc, tb):
559557
await callback(*args, **kwds)
560558
return _exit_wrapper

0 commit comments

Comments
 (0)