Skip to content

Commit

Permalink
bpo-37116: Use PEP 570 syntax for positional-only parameters. (python…
Browse files Browse the repository at this point in the history
  • Loading branch information
serhiy-storchaka authored Jun 1, 2019
1 parent 4a68650 commit 2085bd0
Show file tree
Hide file tree
Showing 34 changed files with 126 additions and 261 deletions.
2 changes: 1 addition & 1 deletion Doc/library/collections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1140,7 +1140,7 @@ variants of :func:`functools.lru_cache`::
class LRU(OrderedDict):
'Limit size, evicting the least recently looked-up key when full'

def __init__(self, maxsize=128, *args, **kwds):
def __init__(self, maxsize=128, /, *args, **kwds):
self.maxsize = maxsize
super().__init__(*args, **kwds)

Expand Down
2 changes: 1 addition & 1 deletion Doc/library/contextlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,7 @@ even further by means of a small helper class::
from contextlib import ExitStack

class Callback(ExitStack):
def __init__(self, callback, *args, **kwds):
def __init__(self, callback, /, *args, **kwds):
super(Callback, self).__init__()
self.callback(callback, *args, **kwds)

Expand Down
2 changes: 1 addition & 1 deletion Doc/library/email.headerregistry.rst
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ headers.
method if it wishes to set additional attributes beyond those provided by
``BaseHeader`` itself. Such an ``init`` method should look like this::

def init(self, *args, **kw):
def init(self, /, *args, **kw):
self._myattr = kw.pop('myattr')
super().init(*args, **kw)

Expand Down
4 changes: 2 additions & 2 deletions Doc/library/functools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ The :mod:`functools` module defines the following functions:
Returning NotImplemented from the underlying comparison function for
unrecognised types is now supported.

.. function:: partial(func, *args, **keywords)
.. function:: partial(func, /, *args, **keywords)

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

def partial(func, *args, **keywords):
def partial(func, /, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = {**keywords, **fkeywords}
return func(*args, *fargs, **newkeywords)
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/inspect.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1022,7 +1022,7 @@ Classes and functions
metatype is in use, cls will be the first element of the tuple.


.. function:: getcallargs(func, *args, **kwds)
.. function:: getcallargs(func, /, *args, **kwds)

Bind the *args* and *kwds* to the argument names of the Python function or
method *func*, as if it was called with them. For bound methods, bind also the
Expand Down
4 changes: 2 additions & 2 deletions Doc/library/operator.rst
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ expect a function argument.
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]


.. function:: methodcaller(name[, args...])
.. function:: methodcaller(name, /, *args, **kwargs)

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

Equivalent to::

def methodcaller(name, *args, **kwargs):
def methodcaller(name, /, *args, **kwargs):
def caller(obj):
return getattr(obj, name)(*args, **kwargs)
return caller
Expand Down
6 changes: 3 additions & 3 deletions Doc/library/string.rst
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ implementation as the built-in :meth:`~str.format` method.

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

.. method:: format(format_string, *args, **kwargs)
.. method:: format(format_string, /, *args, **kwargs)

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


.. method:: substitute(mapping, **kwds)
.. method:: substitute(mapping={}, /, **kwds)

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


.. method:: safe_substitute(mapping, **kwds)
.. method:: safe_substitute(mapping={}, /, **kwds)

Like :meth:`substitute`, except that if placeholders are missing from
*mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ Additional Utility Classes and Functions
The type is roughly equivalent to the following code::

class SimpleNamespace:
def __init__(self, **kwargs):
def __init__(self, /, **kwargs):
self.__dict__.update(kwargs)

def __repr__(self):
Expand Down
4 changes: 2 additions & 2 deletions Doc/library/unittest.mock-examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -848,7 +848,7 @@ Here's an example implementation:

>>> from copy import deepcopy
>>> class CopyingMock(MagicMock):
... def __call__(self, *args, **kwargs):
... def __call__(self, /, *args, **kwargs):
... args = deepcopy(args)
... kwargs = deepcopy(kwargs)
... return super(CopyingMock, self).__call__(*args, **kwargs)
Expand Down Expand Up @@ -1042,7 +1042,7 @@ that it takes arbitrary keyword arguments (``**kwargs``) which are then passed
onto the mock constructor:

>>> class Subclass(MagicMock):
... def _get_child_mock(self, **kwargs):
... def _get_child_mock(self, /, **kwargs):
... return MagicMock(**kwargs)
...
>>> mymock = Subclass()
Expand Down
4 changes: 2 additions & 2 deletions Doc/library/unittest.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1456,7 +1456,7 @@ Test cases

.. versionadded:: 3.1

.. classmethod:: addClassCleanup(function, *args, **kwargs)
.. classmethod:: addClassCleanup(function, /, *args, **kwargs)

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


.. function:: addModuleCleanup(function, *args, **kwargs)
.. function:: addModuleCleanup(function, /, *args, **kwargs)

Add a function to be called after :func:`tearDownModule` to cleanup
resources used during the test class. Functions will be called in reverse
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/weakref.rst
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ the referent is accessed::
import weakref

class ExtendedRef(weakref.ref):
def __init__(self, ob, callback=None, **annotations):
def __init__(self, ob, callback=None, /, **annotations):
super(ExtendedRef, self).__init__(ob, callback)
self.__counter = 0
for k, v in annotations.items():
Expand Down
3 changes: 1 addition & 2 deletions Doc/whatsnew/3.8.rst
Original file line number Diff line number Diff line change
Expand Up @@ -941,8 +941,7 @@ Deprecated
:meth:`profile.Profile.runcall`, :meth:`cProfile.Profile.runcall`,
:meth:`bdb.Bdb.runcall`, :meth:`trace.Trace.runfunc` and
:func:`curses.wrapper`.
- *function* in :func:`unittest.addModuleCleanup` and
:meth:`unittest.TestCase.addCleanup`.
- *function* in :meth:`unittest.TestCase.addCleanup`.
- *fn* in the :meth:`~concurrent.futures.Executor.submit` method of
:class:`concurrent.futures.ThreadPoolExecutor` and
:class:`concurrent.futures.ProcessPoolExecutor`.
Expand Down
29 changes: 10 additions & 19 deletions Lib/_collections_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -821,30 +821,21 @@ def clear(self):
except KeyError:
pass

def update(*args, **kwds):
def update(self, other=(), /, **kwds):
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v
'''
if not args:
raise TypeError("descriptor 'update' of 'MutableMapping' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('update expected at most 1 arguments, got %d' %
len(args))
if args:
other = args[0]
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value

Expand Down
2 changes: 1 addition & 1 deletion Lib/_py_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class ABCMeta(type):
# external code.
_abc_invalidation_counter = 0

def __new__(mcls, name, bases, namespace, **kwargs):
def __new__(mcls, name, bases, namespace, /, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
# Compute set of abstract method names
abstracts = {name
Expand Down
4 changes: 2 additions & 2 deletions Lib/_threading_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
>>> class MyLocal(local):
... number = 2
... def __init__(self, **kw):
... def __init__(self, /, **kw):
... self.__dict__.update(kw)
... def squared(self):
... return self.number ** 2
Expand Down Expand Up @@ -204,7 +204,7 @@ def _patch(self):
class local:
__slots__ = '_local__impl', '__dict__'

def __new__(cls, *args, **kw):
def __new__(cls, /, *args, **kw):
if (args or kw) and (cls.__init__ is object.__init__):
raise TypeError("Initialization arguments are not supported")
self = object.__new__(cls)
Expand Down
46 changes: 10 additions & 36 deletions Lib/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,24 +93,18 @@ class OrderedDict(dict):
# Individual links are kept alive by the hard reference in self.__map.
# Those hard references disappear when a key is deleted from an OrderedDict.

def __init__(*args, **kwds):
def __init__(self, other=(), /, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries. Keyword argument order is preserved.
'''
if not args:
raise TypeError("descriptor '__init__' of 'OrderedDict' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map = {}
self.__update(*args, **kwds)
self.__update(other, **kwds)

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

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

def __init__(*args, **kwds):
def __init__(self, iterable=None, /, **kwds):
'''Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
Expand All @@ -554,14 +548,8 @@ def __init__(*args, **kwds):
>>> c = Counter(a=4, b=2) # a new counter from keyword args
'''
if not args:
raise TypeError("descriptor '__init__' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
super(Counter, self).__init__()
self.update(*args, **kwds)
self.update(iterable, **kwds)

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

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

if not args:
raise TypeError("descriptor 'update' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable is not None:
if isinstance(iterable, _collections_abc.Mapping):
if self:
Expand All @@ -657,7 +638,7 @@ def update(*args, **kwds):
if kwds:
self.update(kwds)

def subtract(*args, **kwds):
def subtract(self, iterable=None, /, **kwds):
'''Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts.
Expand All @@ -673,13 +654,6 @@ def subtract(*args, **kwds):
-1
'''
if not args:
raise TypeError("descriptor 'subtract' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable is not None:
self_get = self.get
if isinstance(iterable, _collections_abc.Mapping):
Expand Down Expand Up @@ -1141,7 +1115,7 @@ def copy(self): return self.__class__(self)
def count(self, item): return self.data.count(item)
def index(self, item, *args): return self.data.index(item, *args)
def reverse(self): self.data.reverse()
def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
def sort(self, /, *args, **kwds): self.data.sort(*args, **kwds)
def extend(self, other):
if isinstance(other, UserList):
self.data.extend(other.data)
Expand Down Expand Up @@ -1240,7 +1214,7 @@ def find(self, sub, start=0, end=_sys.maxsize):
if isinstance(sub, UserString):
sub = sub.data
return self.data.find(sub, start, end)
def format(self, *args, **kwds):
def format(self, /, *args, **kwds):
return self.data.format(*args, **kwds)
def format_map(self, mapping):
return self.data.format_map(mapping)
Expand Down
6 changes: 2 additions & 4 deletions Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,7 @@ def _create_exit_wrapper(cm, cm_exit):
return MethodType(cm_exit, cm)

@staticmethod
def _create_cb_wrapper(*args, **kwds):
callback, *args = args
def _create_cb_wrapper(callback, /, *args, **kwds):
def _exit_wrapper(exc_type, exc, tb):
callback(*args, **kwds)
return _exit_wrapper
Expand Down Expand Up @@ -553,8 +552,7 @@ def _create_async_exit_wrapper(cm, cm_exit):
return MethodType(cm_exit, cm)

@staticmethod
def _create_async_cb_wrapper(*args, **kwds):
callback, *args = args
def _create_async_cb_wrapper(callback, /, *args, **kwds):
async def _exit_wrapper(exc_type, exc, tb):
await callback(*args, **kwds)
return _exit_wrapper
Expand Down
Loading

0 comments on commit 2085bd0

Please sign in to comment.