Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.9] bpo-37116: Use PEP 570 syntax for positional-only parameters. #12620

Merged
merged 11 commits into from Jun 5, 2019
29 changes: 10 additions & 19 deletions Lib/_collections_abc.py
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
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
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
4 changes: 2 additions & 2 deletions Lib/argparse.py
Expand Up @@ -1220,7 +1220,7 @@ class Namespace(_AttributeHolder):
string representation.
"""

def __init__(self, **kwargs):
def __init__(self, /, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])

Expand Down Expand Up @@ -1297,7 +1297,7 @@ def _registry_get(self, registry_name, value, default=None):
# ==================================
# Namespace default accessor methods
# ==================================
def set_defaults(self, **kwargs):
def set_defaults(self, /, **kwargs):
self._defaults.update(kwargs)

# if these defaults match any existing arguments, replace
Expand Down
2 changes: 1 addition & 1 deletion Lib/bdb.py
Expand Up @@ -618,7 +618,7 @@ def runctx(self, cmd, globals, locals):

# This method is more useful to debug a single function call.

def runcall(self, func, *args, **kwds):
def runcall(self, func, /, *args, **kwds):
"""Debug a single function call.

Return the result of the function call.
Expand Down
2 changes: 1 addition & 1 deletion Lib/cProfile.py
Expand Up @@ -103,7 +103,7 @@ def runctx(self, cmd, globals, locals):
return self

# This method is more useful to profile a single function call.
def runcall(self, func, *args, **kw):
def runcall(self, func, /, *args, **kw):
self.enable()
try:
return func(*args, **kw)
Expand Down
65 changes: 12 additions & 53 deletions Lib/collections/__init__.py
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):
serhiy-storchaka marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -997,26 +971,11 @@ def clear(self):
class UserDict(_collections_abc.MutableMapping):

# Start by filling-out the abstract methods
def __init__(*args, **kwargs):
if not args:
raise TypeError("descriptor '__init__' of 'UserDict' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
if args:
dict = args[0]
elif 'dict' in kwargs:
dict = kwargs.pop('dict')
import warnings
warnings.warn("Passing 'dict' as keyword argument is deprecated",
DeprecationWarning, stacklevel=2)
else:
dict = None
def __init__(self, dict=None, /, **kwargs):
self.data = {}
if dict is not None:
self.update(dict)
if len(kwargs):
if kwargs:
self.update(kwargs)
def __len__(self): return len(self.data)
def __getitem__(self, key):
Expand Down Expand Up @@ -1121,7 +1080,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 @@ -1221,7 +1180,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
2 changes: 1 addition & 1 deletion Lib/concurrent/futures/_base.py
Expand Up @@ -544,7 +544,7 @@ def set_exception(self, exception):
class Executor(object):
"""This is an abstract base class for concrete asynchronous executors."""

def submit(self, fn, *args, **kwargs):
def submit(self, fn, /, *args, **kwargs):
"""Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
Expand Down
2 changes: 1 addition & 1 deletion Lib/concurrent/futures/process.py
Expand Up @@ -594,7 +594,7 @@ def _adjust_process_count(self):
p.start()
self._processes[p.pid] = p

def submit(self, fn, *args, **kwargs):
def submit(self, fn, /, *args, **kwargs):
with self._shutdown_lock:
if self._broken:
raise BrokenProcessPool(self._broken)
Expand Down
2 changes: 1 addition & 1 deletion Lib/concurrent/futures/thread.py
Expand Up @@ -142,7 +142,7 @@ def __init__(self, max_workers=None, thread_name_prefix='',
self._initializer = initializer
self._initargs = initargs

def submit(self, fn, *args, **kwargs):
def submit(self, fn, /, *args, **kwargs):
with self._shutdown_lock:
if self._broken:
raise BrokenThreadPool(self._broken)
Expand Down
8 changes: 4 additions & 4 deletions Lib/contextlib.py
Expand Up @@ -377,7 +377,7 @@ def _create_exit_wrapper(cm, cm_exit):
return MethodType(cm_exit, cm)

@staticmethod
def _create_cb_wrapper(callback, *args, **kwds):
def _create_cb_wrapper(callback, /, *args, **kwds):
def _exit_wrapper(exc_type, exc, tb):
callback(*args, **kwds)
return _exit_wrapper
Expand Down Expand Up @@ -426,7 +426,7 @@ def enter_context(self, cm):
self._push_cm_exit(cm, _exit)
return result

def callback(self, callback, *args, **kwds):
def callback(self, callback, /, *args, **kwds):
"""Registers an arbitrary callback and arguments.

Cannot suppress exceptions.
Expand Down Expand Up @@ -536,7 +536,7 @@ def _create_async_exit_wrapper(cm, cm_exit):
return MethodType(cm_exit, cm)

@staticmethod
def _create_async_cb_wrapper(callback, *args, **kwds):
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 Expand Up @@ -571,7 +571,7 @@ def push_async_exit(self, exit):
self._push_async_cm_exit(exit, exit_method)
return exit # Allow use as a decorator

def push_async_callback(self, callback, *args, **kwds):
def push_async_callback(self, callback, /, *args, **kwds):
"""Registers an arbitrary coroutine function and arguments.

Cannot suppress exceptions.
Expand Down
2 changes: 1 addition & 1 deletion Lib/curses/__init__.py
Expand Up @@ -60,7 +60,7 @@ def start_color():
# raises an exception, wrapper() will restore the terminal to a sane state so
# you can read the resulting traceback.

def wrapper(func, *args, **kwds):
def wrapper(func, /, *args, **kwds):
"""Wrapper function that initializes curses and calls another function,
restoring normal keyboard/screen behavior on error.
The callable object 'func' is then passed the main window 'stdscr'
Expand Down
9 changes: 3 additions & 6 deletions Lib/dataclasses.py
Expand Up @@ -962,10 +962,7 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
return cls


# _cls should never be specified by keyword, so start it with an
# underscore. The presence of _cls is used to detect if this
# decorator is being called with parameters or not.
def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False,
unsafe_hash=False, frozen=False):
"""Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class.
Expand All @@ -983,12 +980,12 @@ def wrap(cls):
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)

# See if we're being called as @dataclass or @dataclass().
if _cls is None:
if cls is None:
# We're called with parens.
return wrap

# We're called as @dataclass without parens.
return wrap(_cls)
return wrap(cls)


def fields(class_or_instance):
Expand Down