cpython: 85710aa396ef (original) (raw)
--- a/Doc/library/inspect.rst
+++ b/Doc/library/inspect.rst
@@ -429,6 +429,9 @@ function.
Accepts a wide range of python callables, from plain functions and classes to
:func:functools.partial
objects.
- Raises :exc:
ValueError
if no signature can be provided, and - :exc:
TypeError
if that type of object is not supported. + .. note:: Some callables may not be introspectable in certain implementations of
--- a/Include/object.h +++ b/Include/object.h @@ -492,6 +492,9 @@ PyAPI_FUNC(PyTypeObject *) _PyType_Calcu PyAPI_FUNC(unsigned int) PyType_ClearCache(void); PyAPI_FUNC(void) PyType_Modified(PyTypeObject *); +PyAPI_FUNC(PyObject *) _PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc); +PyAPI_FUNC(PyObject *) _PyType_GetTextSignatureFromInternalDoc(const char *name, const char internal_doc); + / Generic operations on objects */ struct _Py_Identifier; #ifndef Py_LIMITED_API
--- a/Lib/idlelib/idle_test/test_calltips.py +++ b/Lib/idlelib/idle_test/test_calltips.py @@ -55,24 +55,27 @@ class Get_signatureTest(unittest.TestCas gtest(list.new, 'T.new(S, ...) -> a new object with type S, a subtype of T') gtest(list.init,
'x.__init__(...) initializes x; see help(type(x)) for signature')[](#l3.7)
'Initializes self. See help(type(self)) for accurate signature.')[](#l3.8) append_doc = "L.append(object) -> None -- append object to end"[](#l3.9) gtest(list.append, append_doc)[](#l3.10) gtest([].append, append_doc)[](#l3.11) gtest(List.append, append_doc)[](#l3.12)
gtest(types.MethodType, "method(function, instance)")[](#l3.14)
gtest(types.MethodType, "Create a bound instance method object.")[](#l3.15) gtest(SB(), default_tip)[](#l3.16)
def test_multiline_docstring(self): # Test fewer lines than max.
self.assertEqual(signature(list),[](#l3.20)
"list() -> new empty list\n"[](#l3.21)
"list(iterable) -> new list initialized from iterable's items")[](#l3.22)
self.assertEqual(signature(dict),[](#l3.23)
"dict(mapping) -> new dictionary initialized from a mapping object's\n"[](#l3.24)
"(key, value) pairs\n"[](#l3.25)
"dict(iterable) -> new dictionary initialized as if via:\n"[](#l3.26)
"d = {}\n"[](#l3.27)
"for k, v in iterable:"[](#l3.28)
)[](#l3.29)
# Test max lines and line (currently) too long. self.assertEqual(signature(bytes), -"bytes(iterable_of_ints) -> bytes\n" "bytes(string, encoding[, errors]) -> bytes\n" "bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n" #bytes(int) -> bytes object of size given by the parameter initialized with null bytes
--- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -1419,9 +1419,11 @@ def getgeneratorlocals(generator): _WrapperDescriptor = type(type.call) _MethodWrapper = type(all.call) +_ClassMethodWrapper = type(int.dict['from_bytes']) _NonUserDefinedCallables = (_WrapperDescriptor, _MethodWrapper,
_ClassMethodWrapper,[](#l4.11) types.BuiltinFunctionType)[](#l4.12)
@@ -1443,6 +1445,13 @@ def signature(obj): if not callable(obj): raise TypeError('{!r} is not a callable object'.format(obj))
- if (isinstance(obj, _NonUserDefinedCallables) or
ismethoddescriptor(obj) or[](#l4.20)
isinstance(obj, type)):[](#l4.21)
sig = Signature.from_builtin(obj)[](#l4.22)
if sig:[](#l4.23)
return sig[](#l4.24)
+
if isinstance(obj, types.MethodType):
# In this case we skip the first parameter of the underlying
# function (usually self
or cls
).
@@ -1460,13 +1469,9 @@ def signature(obj):
if sig is not None:
return sig
-
if isinstance(obj, types.FunctionType):
return Signature.from_function(obj)
- if isinstance(obj, functools.partial): sig = signature(obj.func) @@ -2033,7 +2038,7 @@ class Signature: name = parse_name(name_node) if name is invalid: return None
if default_node:[](#l4.47)
if default_node and default_node is not _empty:[](#l4.48) try:[](#l4.49) default_node = RewriteSymbolics().visit(default_node)[](#l4.50) o = ast.literal_eval(default_node)[](#l4.51)
@@ -2066,6 +2071,23 @@ class Signature: kind = Parameter.VAR_KEYWORD p(f.args.kwarg, empty)
if parameters and (hasattr(func, '__self__') or[](#l4.56)
isinstance(func, _WrapperDescriptor,) or[](#l4.57)
ismethoddescriptor(func)[](#l4.58)
):[](#l4.59)
name = parameters[0].name[](#l4.60)
if name not in ('self', 'module', 'type'):[](#l4.61)
pass[](#l4.62)
elif getattr(func, '__self__', None):[](#l4.63)
# strip off self (it's already been bound)[](#l4.64)
p = parameters.pop(0)[](#l4.65)
if not p.name in ('self', 'module', 'type'):[](#l4.66)
raise ValueError('Unexpected name ' + repr(p.name) + ', expected self/module/cls/type')[](#l4.67)
else:[](#l4.68)
# for builtins, self parameter is always positional-only
p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)[](#l4.70)
parameters[0] = p[](#l4.71)
+ return cls(parameters, return_annotation=cls.empty)
--- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -925,7 +925,10 @@ class HTMLDoc(Doc): anchor, name, reallink) argspec = None if inspect.isfunction(object) or inspect.isbuiltin(object):
signature = inspect.signature(object)[](#l5.7)
try:[](#l5.8)
signature = inspect.signature(object)[](#l5.9)
except (ValueError, TypeError):[](#l5.10)
signature = None[](#l5.11) if signature:[](#l5.12) argspec = str(signature)[](#l5.13) if realname == '<lambda>':[](#l5.14)
@@ -1319,8 +1322,12 @@ location listed above. skipdocs = 1 title = self.bold(name) + ' = ' + realname argspec = None
if inspect.isfunction(object) or inspect.isbuiltin(object):[](#l5.19)
signature = inspect.signature(object)[](#l5.20)
if inspect.isroutine(object):[](#l5.22)
try:[](#l5.23)
signature = inspect.signature(object)[](#l5.24)
except (ValueError, TypeError):[](#l5.25)
signature = None[](#l5.26) if signature:[](#l5.27) argspec = str(signature)[](#l5.28) if realname == '<lambda>':[](#l5.29)
--- a/Lib/test/test_capi.py +++ b/Lib/test/test_capi.py @@ -125,7 +125,7 @@ class CAPITest(unittest.TestCase): self.assertEqual(_testcapi.docstring_no_signature.text_signature, None) self.assertEqual(_testcapi.docstring_with_invalid_signature.doc,
"docstring_with_invalid_signature (boo)\n"[](#l6.7)
"docstring_with_invalid_signature (module, boo)\n"[](#l6.8) "\n"[](#l6.9) "This docstring has an invalid signature."[](#l6.10) )[](#l6.11)
@@ -133,12 +133,12 @@ class CAPITest(unittest.TestCase): self.assertEqual(_testcapi.docstring_with_signature.doc, "This docstring has a valid signature.")
self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "(sig)")[](#l6.16)
self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "(module, sig)")[](#l6.17)
self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.doc, "This docstring has a valid signature and some extra newlines.") self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.text_signature,
"(parameter)")[](#l6.22)
"(module, parameter)")[](#l6.23)
@unittest.skipUnless(threading, 'Threading required for this test.')
--- a/Lib/test/test_generators.py +++ b/Lib/test/test_generators.py @@ -436,8 +436,8 @@ From the Iterators list, about the types
[s for s in dir(i) if not s.startswith('_')] ['close', 'gi_code', 'gi_frame', 'gi_running', 'send', 'throw'] from test.support import HAVE_DOCSTRINGS ->>> print(i.next.doc if HAVE_DOCSTRINGS else 'x.next() <==> next(x)') -x.next() <==> next(x) +>>> print(i.next.doc if HAVE_DOCSTRINGS else 'Implements next(self).') +Implements next(self). iter(i) is i True import types
--- a/Lib/test/test_genexps.py +++ b/Lib/test/test_genexps.py @@ -222,8 +222,8 @@ Check that generator attributes are pres True >>> from test.support import HAVE_DOCSTRINGS
--- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -1,21 +1,25 @@ +import _testcapi +import collections +import datetime +import functools +import importlib +import inspect +import io +import linecache +import os +from os.path import normcase +import _pickle import re +import shutil import sys import types +import unicodedata import unittest -import inspect -import linecache -import datetime -import collections -import os -import shutil -import functools -import importlib -from os.path import normcase + try: from concurrent.futures import ThreadPoolExecutor except ImportError: ThreadPoolExecutor = None -import _testcapi from test.support import run_unittest, TESTFN, DirsOnSysPath from test.support import MISSING_C_DOCSTRINGS @@ -23,8 +27,6 @@ from test.script_helper import assert_py from test import inspect_fodder as mod from test import inspect_fodder2 as mod2 -# C module for test_findsource_binary -import unicodedata
Functions tested in this suite:
ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode,
@@ -1582,23 +1584,30 @@ class TestSignatureObject(unittest.TestC ...)) def test_signature_on_unsupported_builtins(self):
with self.assertRaisesRegex(ValueError, 'not supported by signature'):[](#l9.52)
inspect.signature(type)[](#l9.53)
with self.assertRaisesRegex(ValueError, 'not supported by signature'):[](#l9.54)
# support for 'wrapper_descriptor'[](#l9.55)
inspect.signature(type.__call__)[](#l9.56)
with self.assertRaisesRegex(ValueError, 'not supported by signature'):[](#l9.57)
# support for 'method-wrapper'[](#l9.58)
inspect.signature(min.__call__)[](#l9.59)
with self.assertRaisesRegex(ValueError, 'no signature found'):[](#l9.60)
# min simply doesn't have a signature (yet)[](#l9.61)
inspect.signature(min)[](#l9.62)
@unittest.skipIf(MISSING_C_DOCSTRINGS, "Signature information for builtins requires docstrings") def test_signature_on_builtins(self):
# min doesn't have a signature (yet)[](#l9.67)
self.assertEqual(inspect.signature(min), None)[](#l9.68)
signature = inspect.signature(_testcapi.docstring_with_signature_with_defaults)[](#l9.70)
self.assertTrue(isinstance(signature, inspect.Signature))[](#l9.71)
def test_unbound_method(o):[](#l9.73)
"""Use this to test unbound methods (things that should have a self)"""[](#l9.74)
signature = inspect.signature(o)[](#l9.75)
self.assertTrue(isinstance(signature, inspect.Signature))[](#l9.76)
self.assertEqual(list(signature.parameters.values())[0].name, 'self')[](#l9.77)
return signature[](#l9.78)
def test_callable(o):[](#l9.80)
"""Use this to test bound methods or normal callables (things that don't expect self)"""[](#l9.81)
signature = inspect.signature(o)[](#l9.82)
self.assertTrue(isinstance(signature, inspect.Signature))[](#l9.83)
if signature.parameters:[](#l9.84)
self.assertNotEqual(list(signature.parameters.values())[0].name, 'self')[](#l9.85)
return signature[](#l9.86)
signature = test_callable(_testcapi.docstring_with_signature_with_defaults)[](#l9.88) def p(name): return signature.parameters[name].default[](#l9.89) self.assertEqual(p('s'), 'avocado')[](#l9.90) self.assertEqual(p('b'), b'bytes')[](#l9.91)
@@ -1611,6 +1620,41 @@ class TestSignatureObject(unittest.TestC self.assertEqual(p('sys'), sys.maxsize) self.assertEqual(p('exp'), sys.maxsize - 1)
test_callable(type)[](#l9.96)
test_callable(object)[](#l9.97)
# normal method[](#l9.99)
# (PyMethodDescr_Type, "method_descriptor")[](#l9.100)
test_unbound_method(_pickle.Pickler.dump)[](#l9.101)
d = _pickle.Pickler(io.StringIO())[](#l9.102)
test_callable(d.dump)[](#l9.103)
# static method[](#l9.105)
test_callable(str.maketrans)[](#l9.106)
test_callable('abc'.maketrans)[](#l9.107)
# class method[](#l9.109)
test_callable(dict.fromkeys)[](#l9.110)
test_callable({}.fromkeys)[](#l9.111)
# wrapper around slot (PyWrapperDescr_Type, "wrapper_descriptor")[](#l9.113)
test_unbound_method(type.__call__)[](#l9.114)
test_unbound_method(int.__add__)[](#l9.115)
test_callable((3).__add__)[](#l9.116)
# _PyMethodWrapper_Type[](#l9.118)
# support for 'method-wrapper'[](#l9.119)
test_callable(min.__call__)[](#l9.120)
class ThisWorksNow:[](#l9.122)
__call__ = type[](#l9.123)
test_callable(ThisWorksNow())[](#l9.124)
- def test_signature_on_builtins_no_signature(self):
with self.assertRaisesRegex(ValueError, 'no signature found for builtin'):[](#l9.128)
inspect.signature(_testcapi.docstring_no_signature)[](#l9.129)
+ def test_signature_on_non_function(self): with self.assertRaisesRegex(TypeError, 'is not a callable object'): inspect.signature(42) @@ -1985,12 +2029,6 @@ class TestSignatureObject(unittest.TestC ((('a', ..., ..., "positional_or_keyword"),), ...))
class ToFail:[](#l9.138)
__call__ = type[](#l9.139)
with self.assertRaisesRegex(ValueError, "not supported by signature"):[](#l9.140)
inspect.signature(ToFail())[](#l9.141)
- - class Wrapped: pass Wrapped.wrapped = lambda a: None
--- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -112,11 +112,24 @@ def _check_signature(func, mock, skipfir def _copy_func_details(func, funcopy): funcopy.name = func.name funcopy.doc = func.doc
- try:
funcopy.__text_signature__ = func.__text_signature__[](#l10.8)
- except AttributeError:
pass[](#l10.10)
we explicitly don't copy func.dict into this copy as it would
expose original attributes that should be mocked
- try:
funcopy.__module__ = func.__module__[](#l10.17)
- except AttributeError:
pass[](#l10.19)
- try:
funcopy.__defaults__ = func.__defaults__[](#l10.21)
- except AttributeError:
pass[](#l10.23)
- try:
funcopy.__kwdefaults__ = func.__kwdefaults__[](#l10.25)
- except AttributeError:
pass[](#l10.27)
--- a/Misc/NEWS +++ b/Misc/NEWS @@ -10,6 +10,10 @@ Release date: 2014-01-19 Core and Builtins ----------------- +- Issue #20189: Four additional builtin types (PyTypeObject,
- PyMethodDescr_Type, _PyMethodWrapper_Type, and PyWrapperDescr_Type)
- have been modified to provide introspection information for builtins. +
- Issue #17825: Cursor "^" is correctly positioned for SyntaxError and IndentationError. @@ -32,6 +36,10 @@ Core and Builtins Library ------- +- Issue #20189: unittest.mock now no longer assumes that any object for
- which it could get an inspect.Signature is a callable written in Python.
- Fix courtesy of Michael Foord. +
- Issue #20311: selector.PollSelector.select() now rounds the timeout away from zero, instead of rounding towards zero. For example, a timeout of one microsecond is now rounded to one millisecond, instead of being rounded to @@ -122,7 +130,7 @@ IDLE --Issue #17390: Add Python version to Idle editor window title bar. Original patches by Edmond Burnett and Kent Johnson.
- +
- Issue #18960: IDLE now ignores the source encoding declaration on the second line if the first line contains anything except a comment. @@ -133,6 +141,16 @@ Tests Tools/Demos ----------- +- Issue #20189: Argument Clinic now ensures that parser functions for
- new are always of type newfunc, the type of the tp_new slot.
- Similarly, parser functions for init are now always of type initproc,
- the type of tp_init. + +- Issue #20189: Argument Clinic now suppresses the docstring for new
- and init functions if no docstring is provided in the input. + +- Issue #20189: Argument Clinic now suppresses the "self" parameter in the
- impl for @staticmethod functions.
--- a/Modules/cryptmodule.c +++ b/Modules/cryptmodule.c @@ -30,7 +30,7 @@ results for a given word. [clinic start generated code]*/ PyDoc_STRVAR(crypt_crypt__doc, -"crypt(word, salt)\n" +"crypt(module, word, salt)\n" "Hash a word with the given salt and return the hashed password.\n" "\n" "word will usually be a user's password. salt (either a random 2 or 16\n" @@ -63,7 +63,7 @@ exit: static PyObject crypt_crypt_impl(PyModuleDef module, const char word, const char salt) -/[clinic end generated code: checksum=a137540bf6862f9935fc112b8bb1d62d6dd1ad02]/ +/[clinic end generated code: checksum=dbfe26a21eb335abefe6a0bbd0a682ea22b9adc0]/ { /* On some platforms (AtheOS) crypt returns NULL for an invalid salt. Return None in that case. XXX Maybe raise an exception? */
--- a/Modules/cursesmodule.c +++ b/Modules/cursesmodule.c @@ -584,7 +584,7 @@ current settings for the window object. [clinic start generated code]*/ PyDoc_STRVAR(curses_window_addch__doc, -"addch([x, y,] ch, [attr])\n" +"addch(self, [x, y,] ch, [attr])\n" "Paint character ch at (y, x) with attributes attr.\n" "\n" " x\n" @@ -651,7 +651,7 @@ exit: static PyObject curses_window_addch_impl(PyObject self, int group_left_1, int x, int y, PyObject ch, int group_right_1, long attr) -/[clinic end generated code: checksum=53d44d79791b30950972b3256bdd464f7426bf82]/ +/[clinic end generated code: checksum=f6eeada77a9ec085125f3a27e4a2095f2a4c50be]*/ { PyCursesWindowObject *cwself = (PyCursesWindowObject *)self; int coordinates_group = group_left_1;
--- a/Modules/datetimemodule.c +++ b/Modules/datetimemodule.c @@ -4159,7 +4159,7 @@ If no tz is specified, uses local timezo [clinic start generated code]*/ PyDoc_STRVAR(datetime_datetime_now__doc, -"now(tz=None)\n" +"now(type, tz=None)\n" "Returns new datetime object representing current time local to tz.\n" "\n" " tz\n" @@ -4171,10 +4171,10 @@ PyDoc_STRVAR(datetime_datetime_now__doc_ {"now", (PyCFunction)datetime_datetime_now, METH_VARARGS|METH_KEYWORDS|METH_CLASS, datetime_datetime_now__doc__}, static PyObject * -datetime_datetime_now_impl(PyTypeObject *cls, PyObject *tz); +datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz); static PyObject * -datetime_datetime_now(PyTypeObject *cls, PyObject *args, PyObject *kwargs) +datetime_datetime_now(PyTypeObject *type, PyObject *args, PyObject *kwargs) { PyObject *return_value = NULL; static char *_keywords[] = {"tz", NULL}; @@ -4184,15 +4184,15 @@ datetime_datetime_now(PyTypeObject *cls, "|O:now", _keywords, &tz)) goto exit;
exit: return return_value; } static PyObject * -datetime_datetime_now_impl(PyTypeObject cls, PyObject tz) -/[clinic end generated code: checksum=ca3d26a423b3f633b260c7622e303f0915a96f7c]/ +datetime_datetime_now_impl(PyTypeObject type, PyObject tz) +/[clinic end generated code: checksum=a6d3ad2c0ab6389075289af3467f7b8eb13f5f5c]/ { PyObject *self; @@ -4202,7 +4202,7 @@ datetime_datetime_now_impl(PyTypeObject if (check_tzinfo_subclass(tz) < 0) return NULL;
- self = datetime_best_possible((PyObject *)type, tz == Py_None ? localtime : gmtime, tz); if (self != NULL && tz != Py_None) {
--- a/Modules/dbmmodule.c +++ b/Modules/dbmmodule.c @@ -279,7 +279,7 @@ Return the value for key if present, oth [clinic start generated code]*/ PyDoc_STRVAR(dbm_dbm_get__doc, -"get(key, [default])\n" +"get(self, key, [default])\n" "Return the value for key if present, otherwise default."); #define DBM_DBM_GET_METHODDEF [](#l15.11) @@ -289,7 +289,7 @@ static PyObject * dbm_dbm_get_impl(dbmobject *dp, const char *key, Py_ssize_clean_t key_length, int group_right_1, PyObject *default_value); static PyObject * -dbm_dbm_get(PyObject *self, PyObject *args) +dbm_dbm_get(dbmobject *dp, PyObject *args) { PyObject *return_value = NULL; const char *key; @@ -311,7 +311,7 @@ dbm_dbm_get(PyObject *self, PyObject *ar PyErr_SetString(PyExc_TypeError, "dbm.dbm.get requires 1 to 2 arguments"); goto exit; }
exit: return return_value; @@ -319,7 +319,7 @@ exit: static PyObject dbm_dbm_get_impl(dbmobject dp, const char key, Py_ssize_clean_t key_length, int group_right_1, PyObject default_value) -/[clinic end generated code: checksum=ca8bf63ec226e71d3cf390749777f7d5b7361478]/ +/[clinic end generated code: checksum=31d5180d6b36f1eafea78ec4391adf3559916379]/ { datum dbm_key, val; @@ -462,7 +462,7 @@ Return a database object. [clinic start generated code]*/ PyDoc_STRVAR(dbmopen__doc__, -"open(filename, flags='r', mode=0o666)\n" +"open(module, filename, flags='r', mode=0o666)\n" "Return a database object.\n" "\n" " filename\n" @@ -499,7 +499,7 @@ exit: static PyObject dbmopen_impl(PyModuleDef module, const char filename, const char flags, int mode) -/[clinic end generated code: checksum=fb265f75641553ccd963f84c143b35c11f9121fc]/ +/[clinic end generated code: checksum=9efae7d3c3b67a365011bf4e463e918901ba6c79]/ { int iflags;
--- a/Modules/_opcode.c +++ b/Modules/opcode.c @@ -21,7 +21,7 @@ Compute the stack effect of the opcode. [clinic start generated code]*/ PyDoc_STRVAR(opcode_stack_effect__doc, -"stack_effect(opcode, [oparg])\n" +"stack_effect(module, opcode, [oparg])\n" "Compute the stack effect of the opcode."); #define _OPCODE_STACK_EFFECT_METHODDEF [](#l16.11) @@ -64,7 +64,7 @@ exit: static int _opcode_stack_effect_impl(PyModuleDef module, int opcode, int group_right_1, int oparg) -/[clinic end generated code: checksum=58fb4f1b174fc92f783dc945ca712fb752a6c283]/ +/[clinic end generated code: checksum=4689140ffda2494a123ea2593fb63445fb039774]*/ { int effect; if (HAS_ARG(opcode)) {
--- a/Modules/_pickle.c +++ b/Modules/pickle.c @@ -3889,7 +3889,7 @@ re-using picklers. [clinic start generated code]*/ PyDoc_STRVAR(pickle_Pickler_clear_memo__doc, -"clear_memo()\n" +"clear_memo(self)\n" "Clears the pickler's "memo".\n" "\n" "The memo is the data structure that remembers which objects the\n" @@ -3904,14 +3904,14 @@ static PyObject * _pickle_Pickler_clear_memo_impl(PicklerObject *self); static PyObject * -_pickle_Pickler_clear_memo(PyObject *self, PyObject *Py_UNUSED(ignored)) -{
+_pickle_Pickler_clear_memo(PicklerObject *self, PyObject *Py_UNUSED(ignored)) +{
} static PyObject _pickle_Pickler_clear_memo_impl(PicklerObject self) -/[clinic end generated code: checksum=015cc3c5befea86cb08b9396938477bebbea4157]/ +/[clinic end generated code: checksum=17b1165d8dcae5a2e90b1703bf5cbbfc26114c5a]/ { if (self->memo) PyMemoTable_Clear(self->memo); @@ -3931,7 +3931,7 @@ Write a pickled representation of the gi [clinic start generated code]/ PyDoc_STRVAR(pickle_Pickler_dump__doc_, -"dump(obj)\n" +"dump(self, obj)\n" "Write a pickled representation of the given object to the open file."); #define PICKLE_PICKLER_DUMP_METHODDEF [](#l17.39) @@ -3939,7 +3939,7 @@ PyDoc_STRVAR(pickle_Pickler_dump__doc static PyObject _pickle_Pickler_dump(PicklerObject self, PyObject obj) -/[clinic end generated code: checksum=b72a69ec98737fabf66dae7c5a3210178bdbd3e6]/ +/[clinic end generated code: checksum=36db7f67c8bc05ca6f17b8ab57c54d64bfd0539e]/ { /* Check whether the Pickler was initialized correctly (issue3664). Developers often forget to call init() in their subclasses, which @@ -4077,7 +4077,7 @@ static int int fix_imports = 1; if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"O|Op:__init__", _keywords,[](#l17.53)
return_value = _pickle_Pickler___init___impl((PicklerObject )self, file, protocol, fix_imports); @@ -4088,7 +4088,7 @@ exit: static int _pickle_Pickler___init___impl(PicklerObject self, PyObject file, PyObject protocol, int fix_imports) -/[clinic end generated code: checksum=d10dfb463511430b4faad9fca07627041a35b96e]/ +/[clinic end generated code: checksum=b055bf46cfb5b92c1863302d075246a68bd89153]/ { _Py_IDENTIFIER(persistent_id); Py_IDENTIFIER(dispatch_table); @@ -4164,7 +4164,7 @@ Remove all items from memo. [clinic start generated code]*/ PyDoc_STRVAR(pickle_PicklerMemoProxy_clear__doc, -"clear()\n" +"clear(self)\n" "Remove all items from memo.");"O|Op:Pickler", _keywords,[](#l17.54) &file, &protocol, &fix_imports))[](#l17.55) goto exit;[](#l17.56)
#define _PICKLE_PICKLERMEMOPROXY_CLEAR_METHODDEF [](#l17.75) @@ -4174,14 +4174,14 @@ static PyObject * _pickle_PicklerMemoProxy_clear_impl(PicklerMemoProxyObject *self); static PyObject * -_pickle_PicklerMemoProxy_clear(PyObject *self, PyObject *Py_UNUSED(ignored)) -{
+_pickle_PicklerMemoProxy_clear(PicklerMemoProxyObject *self, PyObject *Py_UNUSED(ignored)) +{
} static PyObject _pickle_PicklerMemoProxy_clear_impl(PicklerMemoProxyObject self) -/[clinic end generated code: checksum=bf8dd8c8688d0c0f7a2e59a804c47375b740f2f0]/ +/[clinic end generated code: checksum=fb4a5ba40918b3eccc9bc1e9d6875cb2737127a9]/ { if (self->pickler->memo) PyMemoTable_Clear(self->pickler->memo); @@ -4197,7 +4197,7 @@ Copy the memo to a new object. [clinic start generated code]*/ PyDoc_STRVAR(pickle_PicklerMemoProxy_copy__doc_, -"copy()\n" +"copy(self)\n" "Copy the memo to a new object."); #define _PICKLE_PICKLERMEMOPROXY_COPY_METHODDEF [](#l17.103) @@ -4207,14 +4207,14 @@ static PyObject * _pickle_PicklerMemoProxy_copy_impl(PicklerMemoProxyObject *self); static PyObject * -_pickle_PicklerMemoProxy_copy(PyObject *self, PyObject *Py_UNUSED(ignored)) -{
+_pickle_PicklerMemoProxy_copy(PicklerMemoProxyObject *self, PyObject *Py_UNUSED(ignored)) +{
} static PyObject _pickle_PicklerMemoProxy_copy_impl(PicklerMemoProxyObject self) -/[clinic end generated code: checksum=72d46879dc658adbd3d28b5c82dd8dcfa6b9b124]/ +/[clinic end generated code: checksum=3d27d3005725f1828c9a92a38197811c54c64abb]/ { Py_ssize_t i; PyMemoTable memo; @@ -4260,7 +4260,7 @@ Implement pickle support. [clinic start generated code]/ PyDoc_STRVAR(pickle_PicklerMemoProxy___reduce____doc_, -"reduce()\n" +"reduce(self)\n" "Implement pickle support."); #define _PICKLE_PICKLERMEMOPROXY___REDUCE___METHODDEF [](#l17.131) @@ -4270,14 +4270,14 @@ static PyObject * pickle_PicklerMemoProxy___reduce___impl(PicklerMemoProxyObject *self); static PyObject * -pickle_PicklerMemoProxy___reduce(PyObject *self, PyObject *Py_UNUSED(ignored)) -{
+pickle_PicklerMemoProxy___reduce_(PicklerMemoProxyObject *self, PyObject *Py_UNUSED(ignored)) +{
} static PyObject _pickle_PicklerMemoProxy___reduce___impl(PicklerMemoProxyObject self) -/[clinic end generated code: checksum=aad71c4d81d1ed8bf0d32362dd80a29b9f3b0d03]/ +/[clinic end generated code: checksum=2682cf8a3a5027def6328419001b086b047d47c8]/ { PyObject reduce_value, dict_args; PyObject contents = _pickle_PicklerMemoProxy_copy_impl(self); @@ -6299,7 +6299,7 @@ specified therein. [clinic start generated code]/ PyDoc_STRVAR(pickle_Unpickler_load__doc_, -"load()\n" +"load(self)\n" "Load a pickle.\n" "\n" "Read a pickled object representation from the open file object given\n" @@ -6320,7 +6320,7 @@ static PyObject static PyObject _pickle_Unpickler_load_impl(PyObject self) -/[clinic end generated code: checksum=9477099fe6a90748c13ff1a6dd92ba7ab7a89602]/ +/[clinic end generated code: checksum=fb1119422c5e03045d690d1cd6c457f1ca4c585d]/ { UnpicklerObject unpickler = (UnpicklerObject)self; @@ -6363,7 +6363,7 @@ needed. Both arguments passed are str o [clinic start generated code]/ PyDoc_STRVAR(pickle_Unpickler_find_class__doc_, -"find_class(module_name, global_name)\n" +"find_class(self, module_name, global_name)\n" "Return an object from a specified module.\n" "\n" "If necessary, the module will be imported. Subclasses may override\n" @@ -6380,7 +6380,7 @@ static PyObject * _pickle_Unpickler_find_class_impl(UnpicklerObject *self, PyObject *module_name, PyObject *global_name); static PyObject * -_pickle_Unpickler_find_class(PyObject *self, PyObject *args) +_pickle_Unpickler_find_class(UnpicklerObject *self, PyObject *args) { PyObject *return_value = NULL; PyObject *module_name; @@ -6390,7 +6390,7 @@ static PyObject * 2, 2, &module_name, &global_name)) goto exit;
- return_value = _pickle_Unpickler_find_class_impl((UnpicklerObject *)self, module_name, global_name);
exit: return return_value; @@ -6398,7 +6398,7 @@ exit: static PyObject _pickle_Unpickler_find_class_impl(UnpicklerObject self, PyObject module_name, PyObject global_name) -/[clinic end generated code: checksum=15ed4836fd5860425fff9ea7855d4f1f4413c170]/ +/[clinic end generated code: checksum=2b8d5398787c8ac7ea5d45f644433169e441003b]/ { PyObject *global; PyObject *modules_dict; @@ -6617,7 +6617,7 @@ static int const char *errors = "strict"; if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"O|$pss:__init__", _keywords,[](#l17.209)
return_value = _pickle_Unpickler___init___impl((UnpicklerObject )self, file, fix_imports, encoding, errors); @@ -6628,7 +6628,7 @@ exit: static int _pickle_Unpickler___init___impl(UnpicklerObject self, PyObject file, int fix_imports, const char encoding, const char errors) -/[clinic end generated code: checksum=eb1a2cfc7b6f97c33980cff3d3b97d184a382f02]/ +/[clinic end generated code: checksum=a8a9dde29eb4ddd538b45099408ea77e01940692]/ { _Py_IDENTIFIER(persistent_load); @@ -6698,7 +6698,7 @@ Remove all items from memo. [clinic start generated code]/ PyDoc_STRVAR(pickle_UnpicklerMemoProxy_clear__doc_, -"clear()\n" +"clear(self)\n" "Remove all items from memo.");"O|$pss:Unpickler", _keywords,[](#l17.210) &file, &fix_imports, &encoding, &errors))[](#l17.211) goto exit;[](#l17.212)
#define _PICKLE_UNPICKLERMEMOPROXY_CLEAR_METHODDEF [](#l17.231) @@ -6708,14 +6708,14 @@ static PyObject * _pickle_UnpicklerMemoProxy_clear_impl(UnpicklerMemoProxyObject *self); static PyObject * -_pickle_UnpicklerMemoProxy_clear(PyObject *self, PyObject *Py_UNUSED(ignored)) -{
+_pickle_UnpicklerMemoProxy_clear(UnpicklerMemoProxyObject *self, PyObject *Py_UNUSED(ignored)) +{
} static PyObject _pickle_UnpicklerMemoProxy_clear_impl(UnpicklerMemoProxyObject self) -/[clinic end generated code: checksum=07adecee2181e5e268b2ff184360b1d88ad947f2]/ +/[clinic end generated code: checksum=32f6ee47e44405dd587f768f3690d47947bb5a8e]/ { _Unpickler_MemoCleanup(self->unpickler); self->unpickler->memo = Unpickler_NewMemo(self->unpickler->memo_size); @@ -6733,7 +6733,7 @@ Copy the memo to a new object. [clinic start generated code]*/ PyDoc_STRVAR(pickle_UnpicklerMemoProxy_copy__doc, -"copy()\n" +"copy(self)\n" "Copy the memo to a new object."); #define _PICKLE_UNPICKLERMEMOPROXY_COPY_METHODDEF [](#l17.259) @@ -6743,14 +6743,14 @@ static PyObject * _pickle_UnpicklerMemoProxy_copy_impl(UnpicklerMemoProxyObject *self); static PyObject * -_pickle_UnpicklerMemoProxy_copy(PyObject *self, PyObject *Py_UNUSED(ignored)) -{
+_pickle_UnpicklerMemoProxy_copy(UnpicklerMemoProxyObject *self, PyObject *Py_UNUSED(ignored)) +{
} static PyObject _pickle_UnpicklerMemoProxy_copy_impl(UnpicklerMemoProxyObject self) -/[clinic end generated code: checksum=47b9f0cc12c5a54004252e1b4916822cdfa8a881]/ +/[clinic end generated code: checksum=ac3da80efc3b2548aa8b5c5358d0e82e615fce1d]/ { Py_ssize_t i; PyObject new_memo = PyDict_New(); @@ -6789,7 +6789,7 @@ Implement pickling support. [clinic start generated code]/ PyDoc_STRVAR(pickle_UnpicklerMemoProxy___reduce____doc_, -"reduce()\n" +"reduce(self)\n" "Implement pickling support."); #define _PICKLE_UNPICKLERMEMOPROXY___REDUCE___METHODDEF [](#l17.287) @@ -6799,14 +6799,14 @@ static PyObject * pickle_UnpicklerMemoProxy___reduce___impl(UnpicklerMemoProxyObject *self); static PyObject * -pickle_UnpicklerMemoProxy___reduce(PyObject *self, PyObject *Py_UNUSED(ignored)) -{
+pickle_UnpicklerMemoProxy___reduce_(UnpicklerMemoProxyObject *self, PyObject *Py_UNUSED(ignored)) +{
}
static PyObject
_pickle_UnpicklerMemoProxy___reduce___impl(UnpicklerMemoProxyObject self)
-/[clinic end generated code: checksum=2f061bb9ecd9ee8500184c135148a131c46a3b88]/
+/[clinic end generated code: checksum=2373102b7c87d99ba4c4a56b6813d2c84dd61865]/
{
PyObject *reduce_value;
PyObject constructor_args;
@@ -7115,7 +7115,7 @@ 2, so that the pickle data stream is rea
[clinic start generated code]/
PyDoc_STRVAR(pickle_dump__doc_,
-"dump(obj, file, protocol=None, *, fix_imports=True)\n"
+"dump(module, obj, file, protocol=None, *, fix_imports=True)\n"
"Write a pickled representation of obj to the open file object file.\n"
"\n"
"This is equivalent to Pickler(file, protocol).dump(obj)
, but may\n"
@@ -7166,7 +7166,7 @@ exit:
static PyObject *
_pickle_dump_impl(PyModuleDef module, PyObject obj, PyObject file, PyObject protocol, int fix_imports)
-/[clinic end generated code: checksum=eb5c23e64da34477178230b704d2cc9c6b6650ea]/
+/[clinic end generated code: checksum=1d4ff873e13eb840ff275d716d8d4c5554af087c]/
{
PicklerObject pickler = _Pickler_New();
@@ -7218,7 +7218,7 @@ Python 2, so that the pickle data stream
[clinic start generated code]/
PyDoc_STRVAR(pickle_dumps__doc_,
-"dumps(obj, protocol=None, *, fix_imports=True)\n"
+"dumps(module, obj, protocol=None, *, fix_imports=True)\n"
"Return the pickled representation of the object as a bytes object.\n"
"\n"
"The optional protocol argument tells the pickler to use the given\n"
@@ -7260,7 +7260,7 @@ exit:
static PyObject
_pickle_dumps_impl(PyModuleDef module, PyObject obj, PyObject protocol, int fix_imports)
-/[clinic end generated code: checksum=e9b915d61202a9692cb6c6718db74fe54fc9c4d1]/
+/[clinic end generated code: checksum=9c6c0291ef2d2b0856b7d4caecdcb7bad13a23b3]/
{
PyObject *result;
PicklerObject pickler = _Pickler_New();
@@ -7319,7 +7319,7 @@ string instances as bytes objects.
[clinic start generated code]/
PyDoc_STRVAR(pickle_load__doc_,
-"load(file, *, fix_imports=True, encoding='ASCII', errors='strict')\n"
+"load(module, file, *, fix_imports=True, encoding='ASCII', errors='strict')\n"
"Read and return an object from the pickle data stored in a file.\n"
"\n"
"This is equivalent to Unpickler(file).load()
, but may be more\n"
@@ -7372,7 +7372,7 @@ exit:
static PyObject *
_pickle_load_impl(PyModuleDef module, PyObject file, int fix_imports, const char encoding, const char errors)
-/[clinic end generated code: checksum=b41f06970e57acf2fd602e4b7f88e3f3e1e53087]/
+/[clinic end generated code: checksum=2b5b7e5e3a836cf1c53377ce9274a84a8bceef67]/
{
PyObject *result;
UnpicklerObject unpickler = _Unpickler_New();
@@ -7424,7 +7424,7 @@ string instances as bytes objects.
[clinic start generated code]/
PyDoc_STRVAR(pickle_loads__doc_,
-"loads(data, *, fix_imports=True, encoding='ASCII', errors='strict')\n"
+"loads(module, data, *, fix_imports=True, encoding='ASCII', errors='strict')\n"
"Read and return an object from the given pickle data.\n"
"\n"
"The protocol version of the pickle is detected automatically, so no\n"
@@ -7468,7 +7468,7 @@ exit:
static PyObject *
_pickle_loads_impl(PyModuleDef module, PyObject data, int fix_imports, const char encoding, const char errors)
-/[clinic end generated code: checksum=0663de43aca6c21508a777e29d98c9c3a6e7f72d]/
+/[clinic end generated code: checksum=7b21a75997c8f6636e4bf48c663b28f2bfd4eb6a]/
{
PyObject *result;
UnpicklerObject *unpickler = _Unpickler_New();
--- a/Modules/sre.c +++ b/Modules/sre.c @@ -541,7 +541,7 @@ Matches zero or more characters at the b [clinic start generated code]*/ PyDoc_STRVAR(pattern_match__doc, -"match(pattern, pos=0, endpos=sys.maxsize)\n" +"match(self, pattern, pos=0, endpos=sys.maxsize)\n" "Matches zero or more characters at the beginning of the string."); #define PATTERN_MATCH_METHODDEF [](#l18.11) @@ -551,7 +551,7 @@ static PyObject * pattern_match_impl(PatternObject *self, PyObject *pattern, Py_ssize_t pos, Py_ssize_t endpos); static PyObject * -pattern_match(PyObject *self, PyObject *args, PyObject *kwargs) +pattern_match(PatternObject *self, PyObject *args, PyObject *kwargs) { PyObject *return_value = NULL; static char *_keywords[] = {"pattern", "pos", "endpos", NULL}; @@ -563,7 +563,7 @@ pattern_match(PyObject *self, PyObject * "O|nn:match", _keywords, &pattern, &pos, &endpos)) goto exit;
exit: return return_value; @@ -571,7 +571,7 @@ exit: static PyObject pattern_match_impl(PatternObject self, PyObject pattern, Py_ssize_t pos, Py_ssize_t endpos) -/[clinic end generated code: checksum=63e59c5f3019efe6c1f3acdec42b2d3595e14a09]/ +/[clinic end generated code: checksum=4a3865d13638cb7c13dcae1fe58c1a9c35071998]*/ { SRE_STATE state; Py_ssize_t status;
--- a/Modules/_testcapimodule.c +++ b/Modules/_testcapimodule.c @@ -2851,18 +2851,18 @@ PyDoc_STRVAR(docstring_no_signature, ); PyDoc_STRVAR(docstring_with_invalid_signature, -"docstring_with_invalid_signature (boo)\n" +"docstring_with_invalid_signature (module, boo)\n" "\n" "This docstring has an invalid signature." ); PyDoc_STRVAR(docstring_with_signature, -"docstring_with_signature(sig)\n" +"docstring_with_signature(module, sig)\n" "This docstring has a valid signature." ); PyDoc_STRVAR(docstring_with_signature_and_extra_newlines, -"docstring_with_signature_and_extra_newlines(parameter)\n" +"docstring_with_signature_and_extra_newlines(module, parameter)\n" "\n" "\n" "\n" @@ -2870,7 +2870,7 @@ PyDoc_STRVAR(docstring_with_signature_an ); PyDoc_STRVAR(docstring_with_signature_with_defaults, -"docstring_with_signature_with_defaults(s='avocado', b=b'bytes', d=3.14, i=35, n=None, t=True, f=False, local=the_number_three, sys=sys.maxsize, exp=sys.maxsize - 1)\n" +"docstring_with_signature_with_defaults(module, s='avocado', b=b'bytes', d=3.14, i=35, n=None, t=True, f=False, local=the_number_three, sys=sys.maxsize, exp=sys.maxsize - 1)\n" "\n" "\n" "\n"
--- a/Modules/_weakref.c +++ b/Modules/weakref.c @@ -20,7 +20,7 @@ Return the number of weak references to [clinic start generated code]*/ PyDoc_STRVAR(weakref_getweakrefcount__doc, -"getweakrefcount(object)\n" +"getweakrefcount(module, object)\n" "Return the number of weak references to 'object'."); #define _WEAKREF_GETWEAKREFCOUNT_METHODDEF [](#l20.11) @@ -46,7 +46,7 @@ exit: static Py_ssize_t _weakref_getweakrefcount_impl(PyModuleDef module, PyObject object) -/[clinic end generated code: checksum=744fa73ba68c0ee89567e9cb9bea11863270d516]/ +/[clinic end generated code: checksum=dd8ba0730babf263d3db78d260ea7eacf6eb3735]/ { PyWeakReference **list;
--- a/Modules/posixmodule.c +++ b/Modules/posixmodule.c @@ -2430,7 +2430,7 @@ It's an error to use dir_fd or follow_sy [clinic start generated code]/ PyDoc_STRVAR(os_stat__doc__, -"stat(path, , dir_fd=None, follow_symlinks=True)\n" +"stat(module, path, , dir_fd=None, follow_symlinks=True)\n" "Perform a stat system call on the given path.\n" "\n" " path\n" @@ -2481,7 +2481,7 @@ exit: static PyObject os_stat_impl(PyModuleDef module, path_t path, int dir_fd, int follow_symlinks) -/[clinic end generated code: checksum=85a71ad602e89f8e280118da976f70cd2f9abdf1]/ +/[clinic end generated code: checksum=09cc91b4947f9e3b9335c8be998bb7c56f7f8b40]/ { return posix_do_stat("stat", path, dir_fd, follow_symlinks); } @@ -2562,7 +2562,7 @@ Note that most operations will use the e [clinic start generated code]/ PyDoc_STRVAR(os_access__doc__, -"access(path, mode, , dir_fd=None, effective_ids=False, follow_symlinks=True)\n" +"access(module, path, mode, , dir_fd=None, effective_ids=False, follow_symlinks=True)\n" "Use the real uid/gid to test for access to a path.\n" "\n" " path\n" @@ -2622,7 +2622,7 @@ exit: static PyObject os_access_impl(PyModuleDef module, path_t path, int mode, int dir_fd, int effective_ids, int follow_symlinks) -/[clinic end generated code: checksum=636e835c36562a2fc11acab75314634127fdf769]/ +/[clinic end generated code: checksum=6483a51e1fee83da4f8e41cbc8054a701cfed1c5]/ { PyObject return_value = NULL; @@ -2718,7 +2718,7 @@ Return the name of the terminal device c [clinic start generated code]/ PyDoc_STRVAR(os_ttyname__doc__, -"ttyname(fd)\n" +"ttyname(module, fd)\n" "Return the name of the terminal device connected to 'fd'.\n" "\n" " fd\n" @@ -2752,7 +2752,7 @@ exit: static char os_ttyname_impl(PyModuleDef module, int fd) -/[clinic end generated code: checksum=0f368134dc0a7f21f25185e2e6bacf7675fb473a]/ +/[clinic end generated code: checksum=11bbb8b7969155f54bb8a1ec35ac1ebdfd4b0fec]/ { char *ret;
--- a/Modules/unicodedata.c +++ b/Modules/unicodedata.c @@ -129,7 +129,7 @@ not given, ValueError is raised. [clinic start generated code]*/ PyDoc_STRVAR(unicodedata_UCD_decimal__doc__, -"decimal(unichr, default=None)\n" +"decimal(self, unichr, default=None)\n" "Converts a Unicode character into its equivalent decimal value.\n" "\n" "Returns the decimal value assigned to the Unicode character unichr\n" @@ -161,7 +161,7 @@ exit: static PyObject unicodedata_UCD_decimal_impl(PyObject self, PyUnicodeObject unichr, PyObject default_value) -/[clinic end generated code: checksum=73edde0e9cd5913ea174c4fa81504369761b7426]/ +/[clinic end generated code: checksum=01826b179d497d8fd3842c56679ecbd4faddaa95]/ { PyUnicodeObject *v = (PyUnicodeObject *)unichr; int have_old = 0;
--- a/Modules/zlibmodule.c +++ b/Modules/zlibmodule.c @@ -180,7 +180,7 @@ Returns compressed string. [clinic start generated code]/ PyDoc_STRVAR(zlib_compress__doc__, -"compress(bytes, [level])\n" +"compress(module, bytes, [level])\n" "Returns compressed string.\n" "\n" " bytes\n" @@ -228,7 +228,7 @@ exit: static PyObject zlib_compress_impl(PyModuleDef module, Py_buffer bytes, int group_right_1, int level) -/[clinic end generated code: checksum=74648f97e6b9d3cc9cd568d47262d462bded7ed0]/ +/[clinic end generated code: checksum=ce8d4c0a17ecd79c3ffcc032dcdf8ac6830ded1e]/ { PyObject *ReturnVal = NULL; Byte *input, output = NULL; @@ -766,7 +766,7 @@ Call the flush() method to clear these b [clinic start generated code]/ PyDoc_STRVAR(zlib_Decompress_decompress__doc__, -"decompress(data, max_length=0)\n" +"decompress(self, data, max_length=0)\n" "Return a string containing the decompressed version of the data.\n" "\n" " data\n" @@ -787,7 +787,7 @@ static PyObject * zlib_Decompress_decompress_impl(compobject *self, Py_buffer *data, unsigned int max_length); static PyObject * -zlib_Decompress_decompress(PyObject *self, PyObject *args) +zlib_Decompress_decompress(compobject *self, PyObject *args) { PyObject *return_value = NULL; Py_buffer data = {NULL, NULL}; @@ -797,7 +797,7 @@ zlib_Decompress_decompress(PyObject sel "y|O&:decompress", &data, uint_converter, &max_length)) goto exit;
exit: /* Cleanup for data / @@ -809,7 +809,7 @@ exit: static PyObject zlib_Decompress_decompress_impl(compobject self, Py_buffer data, unsigned int max_length) -/[clinic end generated code: checksum=e0058024c4a97b411d2e2197791b89fde175f76f]/ +/[clinic end generated code: checksum=b7fd2e3b23430f57f5a84817189575bc46464901]/ { int err; unsigned int old_length, length = DEFAULTALLOC; @@ -1036,7 +1036,7 @@ Return a copy of the compression object. [clinic start generated code]*/ PyDoc_STRVAR(zlib_Compress_copy__doc__, -"copy()\n" +"copy(self)\n" "Return a copy of the compression object."); #define ZLIB_COMPRESS_COPY_METHODDEF [](#l23.65) @@ -1046,14 +1046,14 @@ static PyObject * zlib_Compress_copy_impl(compobject *self); static PyObject * -zlib_Compress_copy(PyObject *self, PyObject *Py_UNUSED(ignored)) +zlib_Compress_copy(compobject *self, PyObject *Py_UNUSED(ignored)) {
} static PyObject zlib_Compress_copy_impl(compobject self) -/[clinic end generated code: checksum=d57a7911deb7940e85a8d7e65af20b6e2df69000]/ +/[clinic end generated code: checksum=7aa841ad51297eb83250f511a76872e88fdc737e]/ { compobject *retval = NULL; int err;
--- a/Objects/descrobject.c +++ b/Objects/descrobject.c @@ -353,11 +353,17 @@ wrapperdescr_call(PyWrapperDescrObject * static PyObject * method_get_doc(PyMethodDescrObject *descr, void *closure) {
- if (descr->d_method->ml_doc == NULL) {
Py_INCREF(Py_None);[](#l24.8)
return Py_None;[](#l24.9)
- }
- return PyUnicode_FromString(descr->d_method->ml_doc);
- const char *name = descr->d_method->ml_name;
- const char *doc = descr->d_method->ml_doc;
- return _PyType_GetDocFromInternalDoc(name, doc);
+} + +static PyObject * +method_get_text_signature(PyMethodDescrObject *descr, void *closure) +{
- const char *name = descr->d_method->ml_name;
- const char *doc = descr->d_method->ml_doc;
- return _PyType_GetTextSignatureFromInternalDoc(name, doc);
} static PyObject * @@ -425,6 +431,7 @@ static PyMemberDef descr_members[] = { static PyGetSetDef method_getset[] = { {"doc", (getter)method_get_doc}, {"qualname", (getter)descr_get_qualname},
- {"text_signature", (getter)method_get_text_signature}, {0} }; @@ -463,16 +470,23 @@ static PyGetSetDef getset_getset[] = { static PyObject * wrapperdescr_get_doc(PyWrapperDescrObject *descr, void *closure) {
- if (descr->d_base->doc == NULL) {
Py_INCREF(Py_None);[](#l24.39)
return Py_None;[](#l24.40)
- }
- return PyUnicode_FromString(descr->d_base->doc);
- const char *name = descr->d_base->name;
- const char *doc = descr->d_base->doc;
- return _PyType_GetDocFromInternalDoc(name, doc);
+} + +static PyObject * +wrapperdescr_get_text_signature(PyWrapperDescrObject *descr, void *closure) +{
- const char *name = descr->d_base->name;
- const char *doc = descr->d_base->doc;
- return _PyType_GetTextSignatureFromInternalDoc(name, doc);
} static PyGetSetDef wrapperdescr_getset[] = { {"doc", (getter)wrapperdescr_get_doc}, {"qualname", (getter)descr_get_qualname},
- {"text_signature", (getter)wrapperdescr_get_text_signature}, {0} }; @@ -1143,17 +1157,19 @@ wrapper_name(wrapperobject *wp) }
static PyObject * -wrapper_doc(wrapperobject *wp) +wrapper_doc(wrapperobject *wp, void *closure) {
- const char *name = wp->descr->d_base->name;
- const char *doc = wp->descr->d_base->doc;
- return _PyType_GetDocFromInternalDoc(name, doc);
- if (s == NULL) {
Py_INCREF(Py_None);[](#l24.77)
return Py_None;[](#l24.78)
- }
- else {
return PyUnicode_FromString(s);[](#l24.81)
- }
+static PyObject * +wrapper_text_signature(wrapperobject *wp, void *closure) +{
- const char *name = wp->descr->d_base->name;
- const char *doc = wp->descr->d_base->doc;
- return _PyType_GetTextSignatureFromInternalDoc(name, doc);
} static PyObject * @@ -1167,6 +1183,7 @@ static PyGetSetDef wrapper_getsets[] = { {"name", (getter)wrapper_name}, {"qualname", (getter)wrapper_qualname}, {"doc", (getter)wrapper_doc},
--- a/Objects/dictobject.c +++ b/Objects/dictobject.c @@ -1691,37 +1691,71 @@ dict_items(PyDictObject mp) return v; } +/[clinic input] +@classmethod +dict.fromkeys +
+ +Returns a new dict with keys from iterable and values equal to value. +[clinic start generated code]*/ + +PyDoc_STRVAR(dict_fromkeys__doc__, +"fromkeys(type, iterable, value=None)\n" +"Returns a new dict with keys from iterable and values equal to value."); + +#define DICT_FROMKEYS_METHODDEF [](#l25.22)
+ static PyObject * -dict_fromkeys(PyObject *cls, PyObject *args) +dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value); + +static PyObject * +dict_fromkeys(PyTypeObject *type, PyObject *args) {
- PyObject *return_value = NULL;
- PyObject *iterable; PyObject *value = Py_None; +
- if (!PyArg_UnpackTuple(args, "fromkeys",
1, 2,[](#l25.38)
&iterable, &value))[](#l25.39)
goto exit;[](#l25.40)
- return_value = dict_fromkeys_impl(type, iterable, value);
+} + +static PyObject * +dict_fromkeys_impl(PyTypeObject *type, PyObject iterable, PyObject value) +/[clinic end generated code: checksum=008269e1774a379b356841548c04061fd78a9542]/ +{ PyObject it; / iter(seq) */ PyObject *key; PyObject *d; int status;
if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
if (PyDict_CheckExact(seq)) {[](#l25.65)
if (PyDict_CheckExact(iterable)) {[](#l25.66) PyDictObject *mp = (PyDictObject *)d;[](#l25.67) PyObject *oldvalue;[](#l25.68) Py_ssize_t pos = 0;[](#l25.69) PyObject *key;[](#l25.70) Py_hash_t hash;[](#l25.71)
if (dictresize(mp, Py_SIZE(seq))) {[](#l25.73)
if (dictresize(mp, Py_SIZE(iterable))) {[](#l25.74) Py_DECREF(d);[](#l25.75) return NULL;[](#l25.76) }[](#l25.77)
while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {[](#l25.79)
while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {[](#l25.80) if (insertdict(mp, key, hash, value)) {[](#l25.81) Py_DECREF(d);[](#l25.82) return NULL;[](#l25.83)
@@ -1729,18 +1763,18 @@ dict_fromkeys(PyObject *cls, PyObject *a } return d; }
if (PyAnySet_CheckExact(seq)) {[](#l25.88)
if (PyAnySet_CheckExact(iterable)) {[](#l25.89) PyDictObject *mp = (PyDictObject *)d;[](#l25.90) Py_ssize_t pos = 0;[](#l25.91) PyObject *key;[](#l25.92) Py_hash_t hash;[](#l25.93)
if (dictresize(mp, PySet_GET_SIZE(seq))) {[](#l25.95)
if (dictresize(mp, PySet_GET_SIZE(iterable))) {[](#l25.96) Py_DECREF(d);[](#l25.97) return NULL;[](#l25.98) }[](#l25.99)
while (_PySet_NextEntry(seq, &pos, &key, &hash)) {[](#l25.101)
while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {[](#l25.102) if (insertdict(mp, key, hash, value)) {[](#l25.103) Py_DECREF(d);[](#l25.104) return NULL;[](#l25.105)
@@ -1750,7 +1784,7 @@ dict_fromkeys(PyObject *cls, PyObject *a } }
@@ -2176,7 +2210,7 @@ True if D has a key k, else False. [clinic start generated code]/ PyDoc_STRVAR(dict___contains____doc__, -"contains(key)\n" +"contains(self, key)\n" "True if D has a key k, else False."); #define DICT___CONTAINS___METHODDEF [](#l25.123) @@ -2184,7 +2218,7 @@ PyDoc_STRVAR(dict___contains____doc__, static PyObject dict___contains__(PyObject self, PyObject key) -/[clinic end generated code: checksum=402ddb624ba1e4db764bfdfbbee6c1c59d1a11fa]/ +/[clinic end generated code: checksum=c4f85a39baac4776c4275ad5f072f7732c5f0806]/ { register PyDictObject *mp = (PyDictObject *)self; Py_hash_t hash; @@ -2496,10 +2530,6 @@ If E is present and has a .keys() method If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n[](#l25.134) In either case, this is followed by: for k in F: D[k] = F[k]"); -PyDoc_STRVAR(fromkeys__doc__, -"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n[](#l25.138) -v defaults to None."); - PyDoc_STRVAR(clear__doc__, "D.clear() -> None. Remove all items from D."); @@ -2540,8 +2570,7 @@ static PyMethodDef mapp_methods[] = { values__doc__}, {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, update__doc__},
- DICT_FROMKEYS_METHODDEF {"clear", (PyCFunction)dict_clear, METH_NOARGS, clear__doc__}, {"copy", (PyCFunction)dict_copy, METH_NOARGS,
--- a/Objects/methodobject.c +++ b/Objects/methodobject.c @@ -179,75 +179,20 @@ static PyMethodDef meth_methods[] = { {NULL, NULL} }; -/*
- */ -static const char *find_signature(PyCFunctionObject *m) -{
- const char *trace = m->m_ml->ml_doc;
- const char *name = m->m_ml->ml_name;
- size_t length;
- if (!trace || !name)
return NULL;[](#l26.18)
- length = strlen(name);
- if (strncmp(trace, name, length))
return NULL;[](#l26.21)
- trace += length;
- if (*trace != '(')
return NULL;[](#l26.24)
- return trace;
- */ -static const char *skip_signature(const char *trace) -{
- while (*trace && *trace != '\n')
trace++;[](#l26.34)
- return trace;
-} - -static const char *skip_eols(const char *trace) -{
-} - static PyObject * meth_get__text_signature__(PyCFunctionObject *m, void *closure) {
- const char *name = m->m_ml->ml_name;
- const char *doc = m->m_ml->ml_doc;
- return _PyType_GetTextSignatureFromInternalDoc(name, doc);
} static PyObject * meth_get__doc__(PyCFunctionObject *m, void *closure) {
- if (doc)
doc = skip_eols(skip_signature(doc));[](#l26.69)
- else
doc = m->m_ml->ml_doc;[](#l26.71)
- if (!doc) {
Py_INCREF(Py_None);[](#l26.74)
return Py_None;[](#l26.75)
- }
- const char *name = m->m_ml->ml_name;
- const char *doc = m->m_ml->ml_doc;
- return _PyType_GetDocFromInternalDoc(name, doc);
--- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -54,6 +54,83 @@ static unsigned int next_version_tag = 0 static PyObject * slot_tp_new(PyTypeObject *type, PyObject *args, PyObject kwds); +/
- */ +static const char * +find_signature(const char *name, const char *doc) +{
- size_t length;
- if (!doc || !name)
return NULL;[](#l27.17)
- length = strlen(name);
- if (strncmp(doc, name, length))
return NULL;[](#l27.20)
- doc += length;
- if (*doc != '(')
return NULL;[](#l27.23)
- return doc;
- */ +static const char * +skip_signature(const char *doc) +{
- while (*doc && *doc != '\n')
doc++;[](#l27.34)
- return doc;
+} + +static const char * +skip_eols(const char *trace) +{
+} + +static const char * +_PyType_DocWithoutSignature(const char *name, const char *internal_doc) +{
+} + +PyObject * +_PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc) +{
+} + +PyObject * +_PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc) +{
+} + unsigned int PyType_ClearCache(void) { @@ -628,8 +705,11 @@ static PyObject * type_get_doc(PyTypeObject *type, void *context) { PyObject *result;
- if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
return PyUnicode_FromString(type->tp_doc);[](#l27.92)
- if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
const char *name = type->tp_name;[](#l27.94)
const char *doc = type->tp_doc;[](#l27.95)
return _PyType_GetDocFromInternalDoc(name, doc);[](#l27.96)
- } result = PyDict_GetItemId(type->tp_dict, &PyId___doc_); if (result == NULL) { result = Py_None;
@@ -645,6 +725,14 @@ type_get_doc(PyTypeObject *type, void *c return result; } +static PyObject * +type_get_text_signature(PyTypeObject *type, void *context) +{
- const char *name = type->tp_name;
- const char *doc = type->tp_doc;
- return _PyType_GetTextSignatureFromInternalDoc(name, doc);
+} + static int type_set_doc(PyTypeObject *type, PyObject *value, void *context) { @@ -691,6 +779,7 @@ static PyGetSetDef type_getsets[] = { (setter)type_set_abstractmethods, NULL}, {"dict", (getter)type_dict, NULL, NULL}, {"doc", (getter)type_get_doc, (setter)type_set_doc, NULL},
- {"text_signature", (getter)type_get_text_signature, NULL, NULL}, {0} }; @@ -2519,13 +2608,14 @@ PyType_FromSpecWithBases(PyType_Spec sp / need to make a copy of the docstring slot, which usually points to a static string literal */ if (slot->slot == Py_tp_doc) {
size_t len = strlen(slot->pfunc)+1;[](#l27.128)
const char *old_doc = _PyType_DocWithoutSignature(spec->name, slot->pfunc);[](#l27.129)
size_t len = strlen(old_doc)+1;[](#l27.130) char *tp_doc = PyObject_MALLOC(len);[](#l27.131) if (tp_doc == NULL) {[](#l27.132) PyErr_NoMemory();[](#l27.133) goto fail;[](#l27.134) }[](#l27.135)
memcpy(tp_doc, slot->pfunc, len);[](#l27.136)
} @@ -2909,6 +2999,8 @@ static PyMethodDef type_methods[] = { }; PyDoc_STRVAR(type_doc, +/* this text signature cannot be accurate yet. will fix. --larry */ +"type(object_or_name, bases, dict)\n" "type(object) -> the object's type\n" "type(name, bases, dict) -> a new type"); @@ -3480,7 +3572,7 @@ Py_LOCAL(PyObject *) { PyObject **dict; dict = _PyObject_GetDictPtr(obj);memcpy(tp_doc, old_doc, len);[](#l27.137) type->tp_doc = tp_doc;[](#l27.138) }[](#l27.139)
/* It is possible that the object's dict is not initialized [](#l27.154)
/* It is possible that the object's dict is not initialized[](#l27.155) yet. In this case, we will return None for the state.[](#l27.156) We also return None if the dict is empty to make the behavior[](#l27.157) consistent regardless whether the dict was initialized or not.[](#l27.158)
@@ -3788,7 +3880,7 @@ reduce_4(PyObject *obj) Py_DECREF(state); Py_DECREF(listitems); Py_DECREF(dictitems);
} static PyObject * @@ -3813,7 +3905,7 @@ reduce_2(PyObject *obj) } else if (kwargs != NULL) { if (PyDict_Size(kwargs) > 0) {
PyErr_SetString(PyExc_ValueError, [](#l27.172)
PyErr_SetString(PyExc_ValueError,[](#l27.173) "must use protocol 4 or greater to copy this "[](#l27.174) "object; since __getnewargs_ex__ returned "[](#l27.175) "keyword arguments.");[](#l27.176)
@@ -4103,8 +4195,8 @@ PyTypeObject PyBaseObject_Type = { PyObject_GenericGetAttr, /* tp_getattro / PyObject_GenericSetAttr, / tp_setattro / 0, / tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- PyDoc_STR("The most base type"), /* tp_doc */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- PyDoc_STR("object()\nThe most base type"), /* tp_doc / 0, / tp_traverse / 0, / tp_clear / object_richcompare, / tp_richcompare */ @@ -4571,7 +4663,8 @@ PyType_Ready(PyTypeObject *type) */ if (PyDict_GetItemId(type->tp_dict, &PyId___doc_) == NULL) { if (type->tp_doc != NULL) {
PyObject *doc = PyUnicode_FromString(type->tp_doc);[](#l27.192)
const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, type->tp_doc);[](#l27.193)
PyObject *doc = PyUnicode_FromString(old_doc);[](#l27.194) if (doc == NULL)[](#l27.195) goto error;[](#l27.196) if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {[](#l27.197)
@@ -6005,22 +6098,22 @@ typedef struct wrapperbase slotdef; ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) [](#l27.200) ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, [](#l27.201)
"x." NAME "() <==> " DOC)[](#l27.202)
NAME "(self)\n" DOC)[](#l27.203)
#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) [](#l27.204) ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, [](#l27.205)
"x." NAME "(y) <==> x" DOC "y")[](#l27.206)
NAME "(self, value)\nReturns self" DOC "value.")[](#l27.207)
#define BINSLOT(NAME, SLOT, FUNCTION, DOC) [](#l27.208) ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, [](#l27.209)
"x." NAME "(y) <==> x" DOC "y")[](#l27.210)
NAME "(self, value)\nReturns self" DOC "value.")[](#l27.211)
#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) [](#l27.212) ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, [](#l27.213)
"x." NAME "(y) <==> y" DOC "x")[](#l27.214)
NAME "(self, value)\nReturns value" DOC "self.")[](#l27.215)
#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) [](#l27.216) ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, [](#l27.217)
"x." NAME "(y) <==> " DOC)[](#l27.218)
NAME "(self, value)\n" DOC)[](#l27.219)
#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) [](#l27.220) ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, [](#l27.221)
"x." NAME "(y) <==> " DOC)[](#l27.222)
NAME "(self, value)\n" DOC)[](#l27.223)
static slotdef slotdefs[] = { TPSLOT("getattribute", tp_getattr, NULL, NULL, ""), @@ -6028,80 +6121,85 @@ static slotdef slotdefs[] = { TPSLOT("setattr", tp_setattr, NULL, NULL, ""), TPSLOT("delattr", tp_setattr, NULL, NULL, ""), TPSLOT("repr", tp_repr, slot_tp_repr, wrap_unaryfunc,
"x.__repr__() <==> repr(x)"),[](#l27.231)
TPSLOT("hash", tp_hash, slot_tp_hash, wrap_hashfunc,"__repr__(self)\nReturns repr(self)."),[](#l27.232)
"x.__hash__() <==> hash(x)"),[](#l27.234)
FLSLOT("call", tp_call, slot_tp_call, (wrapperfunc)wrap_call,"__hash__(self)\nReturns hash(self)."),[](#l27.235)
"x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),[](#l27.237)
"__call__(self, *args, **kwargs)\nCalls self as a function.",[](#l27.238)
TPSLOT("str", tp_str, slot_tp_str, wrap_unaryfunc,PyWrapperFlag_KEYWORDS),[](#l27.239)
"x.__str__() <==> str(x)"),[](#l27.241)
TPSLOT("getattribute", tp_getattro, slot_tp_getattr_hook,"__str__(self)\nReturns str(self)."),[](#l27.242)
wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),[](#l27.244)
wrap_binaryfunc,[](#l27.245)
TPSLOT("getattr", tp_getattro, slot_tp_getattr_hook, NULL, ""), TPSLOT("setattr", tp_setattro, slot_tp_setattro, wrap_setattr,"__getattribute__(self, name)\nReturns getattr(self, name)."),[](#l27.246)
"x.__setattr__('name', value) <==> x.name = value"),[](#l27.249)
TPSLOT("delattr", tp_setattro, slot_tp_setattro, wrap_delattr,"__setattr__(self, name, value)\nImplements setattr(self, name, value)."),[](#l27.250)
"x.__delattr__('name') <==> del x.name"),[](#l27.252)
TPSLOT("lt", tp_richcompare, slot_tp_richcompare, richcmp_lt,"__delattr__(self, name)\nImplements delattr(self, name)."),[](#l27.253)
"x.__lt__(y) <==> x<y"),[](#l27.255)
TPSLOT("le", tp_richcompare, slot_tp_richcompare, richcmp_le,"__lt__(self, value)\nReturns self<value."),[](#l27.256)
"x.__le__(y) <==> x<=y"),[](#l27.258)
TPSLOT("eq", tp_richcompare, slot_tp_richcompare, richcmp_eq,"__le__(self, value)\nReturns self<=value."),[](#l27.259)
"x.__eq__(y) <==> x==y"),[](#l27.261)
TPSLOT("ne", tp_richcompare, slot_tp_richcompare, richcmp_ne,"__eq__(self, value)\nReturns self==value."),[](#l27.262)
"x.__ne__(y) <==> x!=y"),[](#l27.264)
TPSLOT("gt", tp_richcompare, slot_tp_richcompare, richcmp_gt,"__ne__(self, value)\nReturns self!=value."),[](#l27.265)
"x.__gt__(y) <==> x>y"),[](#l27.267)
TPSLOT("ge", tp_richcompare, slot_tp_richcompare, richcmp_ge,"__gt__(self, value)\nReturns self>value."),[](#l27.268)
"x.__ge__(y) <==> x>=y"),[](#l27.270)
TPSLOT("iter", tp_iter, slot_tp_iter, wrap_unaryfunc,"__ge__(self, value)\nReturns self>=value."),[](#l27.271)
"x.__iter__() <==> iter(x)"),[](#l27.273)
TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,"__iter__(self)\nImplements iter(self)."),[](#l27.274)
"x.__next__() <==> next(x)"),[](#l27.276)
TPSLOT("get", tp_descr_get, slot_tp_descr_get, wrap_descr_get,"__next__(self)\nImplements next(self)."),[](#l27.277)
"descr.__get__(obj[, type]) -> value"),[](#l27.279)
TPSLOT("set", tp_descr_set, slot_tp_descr_set, wrap_descr_set,"__get__(self, instance, owner)\nCalled to get an attribute of instance, which is of type owner."),[](#l27.280)
"descr.__set__(obj, value)"),[](#l27.282)
TPSLOT("delete", tp_descr_set, slot_tp_descr_set,"__set__(self, instance, value)\nSets an attribute of instance to value."),[](#l27.283)
wrap_descr_delete, "descr.__delete__(obj)"),[](#l27.285)
wrap_descr_delete,[](#l27.286)
FLSLOT("init", tp_init, slot_tp_init, (wrapperfunc)wrap_init,"__delete__(instance)\nDeletes an attribute of instance."),[](#l27.287)
"x.__init__(...) initializes x; "[](#l27.289)
"see help(type(x)) for signature",[](#l27.290)
"__init__(self, *args, **kwargs)\n"[](#l27.291)
"Initializes self. See help(type(self)) for accurate signature.",[](#l27.292) PyWrapperFlag_KEYWORDS),[](#l27.293)
- TPSLOT("new", tp_new, slot_tp_new, NULL,
"__new__(cls, *args, **kwargs)\n"[](#l27.296)
TPSLOT("del", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""), BINSLOT("add", nb_add, slot_nb_add,"Creates new object. See help(cls) for accurate signature."),[](#l27.297)
"+"),[](#l27.301)
"+"),[](#l27.304)
"-"),[](#l27.307)
"-"),[](#l27.310)
"*"),[](#l27.313)
"*"),[](#l27.316)
"%"),[](#l27.319)
"%"),[](#l27.322)
"divmod(x, y)"),[](#l27.325)
RBINSLOTNOTINFIX("rdivmod", nb_divmod, slot_nb_divmod,"__divmod__(self, value)\nReturns divmod(self, value)."),[](#l27.326)
"divmod(y, x)"),[](#l27.328)
NBSLOT("pow", nb_power, slot_nb_power, wrap_ternaryfunc,"__rdivmod__(self, value)\nReturns divmod(value, self)."),[](#l27.329)
"x.__pow__(y[, z]) <==> pow(x, y[, z])"),[](#l27.331)
NBSLOT("rpow", nb_power, slot_nb_power, wrap_ternaryfunc_r,"__pow__(self, value, mod=None)\nReturns pow(self, value, mod)."),[](#l27.332)
"y.__rpow__(x[, z]) <==> pow(x, y[, z])"),[](#l27.334)
- UNSLOT("neg", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
- UNSLOT("pos", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
"__rpow__(self, value, mod=None)\nReturns pow(value, self, mod)."),[](#l27.337)
- UNSLOT("neg", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
- UNSLOT("pos", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"), UNSLOT("abs", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
"abs(x)"),[](#l27.341)
"self != 0"),[](#l27.346)
- UNSLOT("invert", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"), BINSLOT("lshift", nb_lshift, slot_nb_lshift, "<<"), RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), @@ -6113,9 +6211,9 @@ static slotdef slotdefs[] = { BINSLOT("or", nb_or, slot_nb_or, "|"), RBINSLOT("ror", nb_or, slot_nb_or, "|"), UNSLOT("int", nb_int, slot_nb_int, wrap_unaryfunc,
"int(x)"),[](#l27.355)
"float(x)"),[](#l27.358)
IBSLOT("iadd", nb_inplace_add, slot_nb_inplace_add, wrap_binaryfunc, "+="), IBSLOT("isub", nb_inplace_subtract, slot_nb_inplace_subtract, @@ -6145,45 +6243,48 @@ static slotdef slotdefs[] = { IBSLOT("itruediv", nb_inplace_true_divide, slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), NBSLOT("index", nb_index, slot_nb_index, wrap_unaryfunc,"float(self)"),[](#l27.359)
"x[y:z] <==> x[y.__index__():z.__index__()]"),[](#l27.367)
"__index__(self)\n"[](#l27.369)
"Returns self converted to an integer, if self is suitable"[](#l27.370)
MPSLOT("len", mp_length, slot_mp_length, wrap_lenfunc,"for use as an index into a list."),[](#l27.371)
"x.__len__() <==> len(x)"),[](#l27.373)
MPSLOT("getitem", mp_subscript, slot_mp_subscript, wrap_binaryfunc,"__len__(self)\nReturns len(self)."),[](#l27.374)
"x.__getitem__(y) <==> x[y]"),[](#l27.377)
MPSLOT("setitem", mp_ass_subscript, slot_mp_ass_subscript, wrap_objobjargproc,"__getitem__(self, key)\nReturns self[key]."),[](#l27.378)
"x.__setitem__(i, y) <==> x[i]=y"),[](#l27.381)
MPSLOT("delitem", mp_ass_subscript, slot_mp_ass_subscript, wrap_delitem,"__setitem__(self, key, value)\nSets self[key] to value."),[](#l27.382)
"x.__delitem__(y) <==> del x[y]"),[](#l27.385)
"__delitem__(key)\nDeletes self[key]."),[](#l27.386)
SQSLOT("len", sq_length, slot_sq_length, wrap_lenfunc,
"x.__len__() <==> len(x)"),[](#l27.389)
/* Heap types defining add/mul have sq_concat/sq_repeat == NULL. The logic in abstract.c always falls back to nb_add/nb_multiply in this case. Defining both the nb_* and the sq_* slots to call the user-defined methods has unexpected side-effects, as shown by test_descr.notimplemented() */ SQSLOT("add", sq_concat, NULL, wrap_binaryfunc,"__len__(self)\nReturns len(self)."),[](#l27.390)
"x.__add__(y) <==> x+y"),[](#l27.397)
SQSLOT("mul", sq_repeat, NULL, wrap_indexargfunc,"__add__(self, value)\nReturns self+value."),[](#l27.398)
"x.__mul__(n) <==> x*n"),[](#l27.400)
SQSLOT("rmul", sq_repeat, NULL, wrap_indexargfunc,"__mul__(self, value)\nReturns self*value.n"),[](#l27.401)
"x.__rmul__(n) <==> n*x"),[](#l27.403)
SQSLOT("getitem", sq_item, slot_sq_item, wrap_sq_item,"__rmul__(self, value)\nReturns self*value."),[](#l27.404)
"x.__getitem__(y) <==> x[y]"),[](#l27.406)
SQSLOT("setitem", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,"__getitem__(self, key)\nReturns self[key]."),[](#l27.407)
"x.__setitem__(i, y) <==> x[i]=y"),[](#l27.409)
SQSLOT("delitem", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,"__setitem__(self, key, value)\nSets self[key] to value."),[](#l27.410)
"x.__delitem__(y) <==> del x[y]"),[](#l27.412)
SQSLOT("contains", sq_contains, slot_sq_contains, wrap_objobjproc,"__delitem__(self, key)\nDeletes self[key]."),[](#l27.413)
"x.__contains__(y) <==> y in x"),[](#l27.415)
SQSLOT("iadd", sq_inplace_concat, NULL,"__contains__(self, key)\nReturns key in self."),[](#l27.416)
wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),[](#l27.418)
wrap_binaryfunc,[](#l27.419)
SQSLOT("imul", sq_inplace_repeat, NULL,"__iadd__(self, value)\nImplements self+=value."),[](#l27.420)
wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),[](#l27.422)
wrap_indexargfunc,[](#l27.423)
"__imul__(self, value)\nImplements self*=value."),[](#l27.424)
--- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -12900,7 +12900,7 @@ PyDoc_STRVAR(unicode_maketrans__doc__, {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__}, static PyObject * -unicode_maketrans_impl(void *null, PyObject *x, PyObject *y, PyObject *z); +unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z); static PyObject * unicode_maketrans(void *null, PyObject *args) @@ -12914,15 +12914,15 @@ unicode_maketrans(void *null, PyObject * "O|UU:maketrans", &x, &y, &z)) goto exit;
exit: return return_value; } static PyObject * -unicode_maketrans_impl(void *null, PyObject *x, PyObject y, PyObject z) -/[clinic end generated code: checksum=7f76f414a0dfd0c614e0d4717872eeb520516da7]/ +unicode_maketrans_impl(PyObject *x, PyObject y, PyObject z) +/[clinic end generated code: checksum=90a3de8c494b304687e1e0d7e5fa8ba78eac6533]/ { PyObject *new = NULL, *key, *value; Py_ssize_t i = 0;
--- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -1325,7 +1325,7 @@ builtin_len(PyObject *self, PyObject *v) } PyDoc_STRVAR(len_doc, -"len(object) -> integer\n[](#l29.7) +"len(module, object)\n[](#l29.8) \n[](#l29.9) Return the number of items of a sequence or mapping.");
--- a/Python/import.c +++ b/Python/import.c @@ -232,7 +232,7 @@ On platforms without threads, return Fal [clinic start generated code]/ PyDoc_STRVAR(imp_lock_held__doc_, -"lock_held()\n" +"lock_held(module)\n" "Return True if the import lock is currently held, else False.\n" "\n" "On platforms without threads, return False."); @@ -251,7 +251,7 @@ static PyObject static PyObject _imp_lock_held_impl(PyModuleDef module) -/[clinic end generated code: checksum=ede1cafb78eb22e3009602f684c8b780e2b82d62]/ +/[clinic end generated code: checksum=17172a9917d389dd1564e2108fec34d23aecb6c2]/ { #ifdef WITH_THREAD return PyBool_FromLong(import_lock_thread != -1); @@ -270,7 +270,7 @@ modules. On platforms without threads, t [clinic start generated code]/ PyDoc_STRVAR(imp_acquire_lock__doc_, -"acquire_lock()\n" +"acquire_lock(module)\n" "Acquires the interpreter's import lock for the current thread.\n" "\n" "This lock should be used by import hooks to ensure thread-safety when importing\n" @@ -290,7 +290,7 @@ static PyObject static PyObject _imp_acquire_lock_impl(PyModuleDef module) -/[clinic end generated code: checksum=5b520b2416c5954a7cf0ed30955d68abe20b5868]/ +/[clinic end generated code: checksum=20db30e18f6b8758386fe06907edb3f8e43080d7]/ { #ifdef WITH_THREAD PyImport_AcquireLock(); @@ -308,7 +308,7 @@ On platforms without threads, this funct [clinic start generated code]*/ PyDoc_STRVAR(imp_release_lock__doc, -"release_lock()\n" +"release_lock(module)\n" "Release the interpreter's import lock.\n" "\n" "On platforms without threads, this function does nothing."); @@ -327,7 +327,7 @@ static PyObject static PyObject _imp_release_lock_impl(PyModuleDef module) -/[clinic end generated code: checksum=efcd9d2923294c04371596e7f6d66a706d43fcac]/ +/[clinic end generated code: checksum=17749fd7752d2c392447a1f83c5d371f54d7ebd3]/ { #ifdef WITH_THREAD if (_PyImport_ReleaseLock() < 0) { @@ -927,7 +927,7 @@ Changes code.co_filename to specify the [clinic start generated code]/ PyDoc_STRVAR(imp__fix_co_filename__doc_, -"_fix_co_filename(code, path)\n" +"_fix_co_filename(module, code, path)\n" "Changes code.co_filename to specify the passed-in file path.\n" "\n" " code\n" @@ -960,7 +960,7 @@ exit: static PyObject _imp__fix_co_filename_impl(PyModuleDef module, PyCodeObject code, PyObject path) -/[clinic end generated code: checksum=4f55bad308072b30ad1921068fc4ce85bd2b39bf]/ +/[clinic end generated code: checksum=d32cf2b2e0480c714f909921cc9e55d763b39dd5]/ { update_compiled_module(code, path); @@ -1823,7 +1823,7 @@ Returns the list of file suffixes used t [clinic start generated code]/ PyDoc_STRVAR(imp_extension_suffixes__doc_, -"extension_suffixes()\n" +"extension_suffixes(module)\n" "Returns the list of file suffixes used to identify extension modules."); #define _IMP_EXTENSION_SUFFIXES_METHODDEF [](#l30.83) @@ -1840,7 +1840,7 @@ static PyObject static PyObject _imp_extension_suffixes_impl(PyModuleDef module) -/[clinic end generated code: checksum=82fb35d8429a429a4dc80c84b45b1aad73ff1de7]/ +/[clinic end generated code: checksum=625c8f11a5bbd4b85373f0a54f7f3ef19c55beb4]/ { PyObject list; const char suffix; @@ -1878,7 +1878,7 @@ Initializes a built-in module. [clinic start generated code]/ PyDoc_STRVAR(imp_init_builtin__doc_, -"init_builtin(name)\n" +"init_builtin(module, name)\n" "Initializes a built-in module."); #define _IMP_INIT_BUILTIN_METHODDEF [](#l30.101) @@ -1905,7 +1905,7 @@ exit: static PyObject _imp_init_builtin_impl(PyModuleDef module, PyObject name) -/[clinic end generated code: checksum=59239206e5b2fb59358066e72fd0e72e55a7baf5]/ +/[clinic end generated code: checksum=a4e4805a523757cd3ddfeec6e5b16740678fed6a]/ { int ret; PyObject m; @@ -1932,7 +1932,7 @@ Initializes a frozen module. [clinic start generated code]/ PyDoc_STRVAR(imp_init_frozen__doc_, -"init_frozen(name)\n" +"init_frozen(module, name)\n" "Initializes a frozen module."); #define _IMP_INIT_FROZEN_METHODDEF [](#l30.119) @@ -1959,7 +1959,7 @@ exit: static PyObject _imp_init_frozen_impl(PyModuleDef module, PyObject name) -/[clinic end generated code: checksum=503fcc3de9961263e4d9484259af357a7d287a0b]/ +/[clinic end generated code: checksum=2a58c119dd3e121cf5a9924f936cfd7b40253c12]/ { int ret; PyObject m; @@ -1986,7 +1986,7 @@ Create a code object for a frozen module [clinic start generated code]/ PyDoc_STRVAR(imp_get_frozen_object__doc_, -"get_frozen_object(name)\n" +"get_frozen_object(module, name)\n" "Create a code object for a frozen module."); #define _IMP_GET_FROZEN_OBJECT_METHODDEF [](#l30.137) @@ -2013,7 +2013,7 @@ exit: static PyObject _imp_get_frozen_object_impl(PyModuleDef module, PyObject name) -/[clinic end generated code: checksum=7a6423a4daf139496b9a394ff3ac6130089d1cba]/ +/[clinic end generated code: checksum=94c9108b58dda80d187fef21275a009bd0f91e96]/ { return get_frozen_object(name); } @@ -2028,7 +2028,7 @@ Returns True if the module name is of a [clinic start generated code]/ PyDoc_STRVAR(imp_is_frozen_package__doc_, -"is_frozen_package(name)\n" +"is_frozen_package(module, name)\n" "Returns True if the module name is of a frozen package."); #define _IMP_IS_FROZEN_PACKAGE_METHODDEF [](#l30.155) @@ -2055,7 +2055,7 @@ exit: static PyObject _imp_is_frozen_package_impl(PyModuleDef module, PyObject name) -/[clinic end generated code: checksum=dc7e361ea30b6945b8bbe7266d7b9a5ea433b510]/ +/[clinic end generated code: checksum=17a342b94dbe859cdfc361bc8a6bc1b3cb163364]/ { return is_frozen_package(name); } @@ -2070,7 +2070,7 @@ Returns True if the module name correspo [clinic start generated code]/ PyDoc_STRVAR(imp_is_builtin__doc_, -"is_builtin(name)\n" +"is_builtin(module, name)\n" "Returns True if the module name corresponds to a built-in module."); #define _IMP_IS_BUILTIN_METHODDEF [](#l30.173) @@ -2097,7 +2097,7 @@ exit: static PyObject _imp_is_builtin_impl(PyModuleDef module, PyObject name) -/[clinic end generated code: checksum=353938c1d55210a1e3850d3ccba7539d02165cac]/ +/[clinic end generated code: checksum=51c6139dcfd9bee1f40980ea68b7797f8489d69a]/ { return PyLong_FromLong(is_builtin(name)); } @@ -2112,7 +2112,7 @@ Returns True if the module name correspo [clinic start generated code]/ PyDoc_STRVAR(imp_is_frozen__doc_, -"is_frozen(name)\n" +"is_frozen(module, name)\n" "Returns True if the module name corresponds to a frozen module."); #define _IMP_IS_FROZEN_METHODDEF [](#l30.191) @@ -2139,7 +2139,7 @@ exit: static PyObject _imp_is_frozen_impl(PyModuleDef module, PyObject name) -/[clinic end generated code: checksum=978b547ddcb76fa6c4a181ad53569c9acf382c7b]/ +/[clinic end generated code: checksum=4b079fb45a495835056ea5604735d552d222be5c]/ { const struct frozen p; @@ -2161,7 +2161,7 @@ Loads an extension module. [clinic start generated code]/ PyDoc_STRVAR(imp_load_dynamic__doc, -"load_dynamic(name, path, file=None)\n" +"load_dynamic(module, name, path, file=None)\n" "Loads an extension module."); #define _IMP_LOAD_DYNAMIC_METHODDEF [](#l30.209) @@ -2190,7 +2190,7 @@ exit: static PyObject * _imp_load_dynamic_impl(PyModuleDef module, PyObject name, PyObject path, PyObject file) -/[clinic end generated code: checksum=6795f65d9ce003ccaf08e4e8eef484dc52e262d0]/ +/[clinic end generated code: checksum=63e051fd0d0350c785bf185be41b0892f9920622]/ { PyObject *mod; FILE *fp;
--- a/Tools/clinic/clinic.py +++ b/Tools/clinic/clinic.py @@ -139,9 +139,9 @@ def is_legal_py_identifier(s):
so if they're used Argument Clinic will add "_value" to the end
of the name in C.
c_keywords = set(""" -asm auto break case char cls const continue default do double -else enum extern float for goto if inline int long module null -register return self short signed sizeof static struct switch +asm auto break case char const continue default do double +else enum extern float for goto if inline int long +register return short signed sizeof static struct switch typedef typeof union unsigned void volatile while """.strip().split()) @@ -635,6 +635,9 @@ methoddef_define def output_templates(self, f): parameters = list(f.parameters.values())
assert parameters[](#l31.20)
assert isinstance(parameters[0].converter, self_converter)[](#l31.21)
del parameters[0][](#l31.22) converters = [p.converter for p in parameters][](#l31.23)
has_option_groups = parameters and (parameters[0].group or parameters[-1].group) @@ -679,8 +682,11 @@ methoddef_define return_value_declaration = "PyObject *return_value = NULL;" methoddef_define = templates['methoddef_define']
docstring_prototype = templates['docstring_prototype'][](#l31.30)
docstring_definition = templates['docstring_definition'][](#l31.31)
if new_or_init and not f.docstring:[](#l31.32)
docstring_prototype = docstring_definition = ''[](#l31.33)
else:[](#l31.34)
docstring_prototype = templates['docstring_prototype'][](#l31.35)
docstring_definition = templates['docstring_definition'][](#l31.36) impl_definition = templates['impl_definition'][](#l31.37) impl_prototype = parser_prototype = parser_definition = None[](#l31.38)
@@ -858,6 +864,8 @@ methoddef_define add, output = text_accumulator() parameters = list(f.parameters.values())
if isinstance(parameters[0].converter, self_converter):[](#l31.44)
del parameters[0][](#l31.45)
groups = [] group = None @@ -936,14 +944,69 @@ methoddef_define data = CRenderData() parameters = list(f.parameters.values())
assert parameters, "We should always have a 'self' at this point!"[](#l31.53)
+ converters = [p.converter for p in parameters]
templates = self.output_templates(f)[](#l31.57)
f_self = parameters[0][](#l31.59)
selfless = parameters[1:][](#l31.60)
assert isinstance(f_self.converter, self_converter), "No self parameter in " + repr(f.full_name) + "!"[](#l31.61)
last_group = 0[](#l31.63)
first_optional = len(selfless)[](#l31.64)
positional = selfless and selfless[-1].kind == inspect.Parameter.POSITIONAL_ONLY[](#l31.65)
new_or_init = f.kind in (METHOD_NEW, METHOD_INIT)[](#l31.66)
default_return_converter = (not f.return_converter or[](#l31.67)
f.return_converter.type == 'PyObject *')[](#l31.68)
has_option_groups = False[](#l31.69)
# offset i by -1 because first_optional needs to ignore self[](#l31.71)
for i, p in enumerate(parameters, -1):[](#l31.72)
c = p.converter[](#l31.73)
if (i != -1) and (p.default is not unspecified):[](#l31.75)
first_optional = min(first_optional, i)[](#l31.76)
# insert group variable[](#l31.78)
group = p.group[](#l31.79)
if last_group != group:[](#l31.80)
last_group = group[](#l31.81)
if group:[](#l31.82)
group_name = self.group_to_variable_name(group)[](#l31.83)
data.impl_arguments.append(group_name)[](#l31.84)
data.declarations.append("int " + group_name + " = 0;")[](#l31.85)
data.impl_parameters.append("int " + group_name)[](#l31.86)
has_option_groups = True[](#l31.87)
c.render(p, data)[](#l31.89)
if has_option_groups and (not positional):[](#l31.91)
fail("You cannot use optional groups ('[' and ']')\nunless all parameters are positional-only ('/').")[](#l31.92)
# HACK[](#l31.94)
# when we're METH_O, but have a custom return converter,[](#l31.95)
# we use "impl_parameters" for the parsing function[](#l31.96)
# because that works better. but that means we must[](#l31.97)
# supress actually declaring the impl's parameters[](#l31.98)
# as variables in the parsing function. but since it's[](#l31.99)
# METH_O, we have exactly one anyway, so we know exactly[](#l31.100)
# where it is.[](#l31.101)
if ("METH_O" in templates['methoddef_define'] and[](#l31.102)
not default_return_converter):[](#l31.103)
data.declarations.pop(0)[](#l31.104)
+ template_dict = {} full_name = f.full_name template_dict['full_name'] = full_name
name = full_name.rpartition('.')[2][](#l31.111)
if new_or_init:[](#l31.112)
name = f.cls.name[](#l31.113)
else:[](#l31.114)
name = f.name[](#l31.115)
+ template_dict['name'] = name if f.c_basename: @@ -953,6 +1016,7 @@ methoddef_define if fields[-1] == 'new': fields.pop() c_basename = "_".join(fields) + template_dict['c_basename'] = c_basename methoddef_name = "{}_METHODDEF".format(c_basename.upper()) @@ -960,67 +1024,7 @@ methoddef_define template_dict['docstring'] = self.docstring_for_c_string(f)
positional = has_option_groups = False[](#l31.132)
first_optional = len(parameters)[](#l31.134)
if parameters:[](#l31.136)
last_group = 0[](#l31.137)
for i, p in enumerate(parameters):[](#l31.139)
c = p.converter[](#l31.140)
if p.default is not unspecified:[](#l31.142)
first_optional = min(first_optional, i)[](#l31.143)
# insert group variable[](#l31.145)
group = p.group[](#l31.146)
if last_group != group:[](#l31.147)
last_group = group[](#l31.148)
if group:[](#l31.149)
group_name = self.group_to_variable_name(group)[](#l31.150)
data.impl_arguments.append(group_name)[](#l31.151)
data.declarations.append("int " + group_name + " = 0;")[](#l31.152)
data.impl_parameters.append("int " + group_name)[](#l31.153)
has_option_groups = True[](#l31.154)
c.render(p, data)[](#l31.155)
positional = parameters[-1].kind == inspect.Parameter.POSITIONAL_ONLY[](#l31.157)
if has_option_groups and (not positional):[](#l31.158)
fail("You cannot use optional groups ('[' and ']')\nunless all parameters are positional-only ('/').")[](#l31.159)
# HACK[](#l31.161)
# when we're METH_O, but have a custom[](#l31.162)
# return converter, we use[](#l31.163)
# "impl_parameters" for the parsing[](#l31.164)
# function because that works better.[](#l31.165)
# but that means we must supress actually[](#l31.166)
# declaring the impl's parameters as variables[](#l31.167)
# in the parsing function. but since it's[](#l31.168)
# METH_O, we only have one anyway, so we don't[](#l31.169)
# have any problem finding it.[](#l31.170)
default_return_converter = (not f.return_converter or[](#l31.171)
f.return_converter.type == 'PyObject *')[](#l31.172)
if (len(parameters) == 1 and[](#l31.173)
parameters[0].kind == inspect.Parameter.POSITIONAL_ONLY and[](#l31.174)
not converters[0].is_optional() and[](#l31.175)
isinstance(converters[0], object_converter) and[](#l31.176)
converters[0].format_unit == 'O' and[](#l31.177)
not default_return_converter):[](#l31.178)
data.declarations.pop(0)[](#l31.180)
# now insert our "self" (or whatever) parameters[](#l31.182)
# (we deliberately don't call render on self converters)[](#l31.183)
stock_self = self_converter('self', f)[](#l31.184)
template_dict['self_name'] = stock_self.name[](#l31.185)
template_dict['self_type'] = stock_self.type[](#l31.186)
data.impl_parameters.insert(0, f.self_converter.type + ("" if f.self_converter.type.endswith('*') else " ") + f.self_converter.name)[](#l31.187)
if f.self_converter.type != stock_self.type:[](#l31.188)
self_cast = '(' + f.self_converter.type + ')'[](#l31.189)
else:[](#l31.190)
self_cast = ''[](#l31.191)
data.impl_arguments.insert(0, self_cast + stock_self.name)[](#l31.192)
f_self.converter.set_template_dict(template_dict)[](#l31.193)
f.return_converter.render(f, data) template_dict['impl_return_type'] = f.return_converter.type @@ -1036,15 +1040,16 @@ methoddef_define template_dict['cleanup'] = "".join(data.cleanup) template_dict['return_value'] = data.return_value
# used by unpack tuple[](#l31.201)
template_dict['unpack_min'] = str(first_optional)[](#l31.202)
template_dict['unpack_max'] = str(len(parameters))[](#l31.203)
# used by unpack tuple code generator[](#l31.204)
ignore_self = -1 if isinstance(converters[0], self_converter) else 0[](#l31.205)
unpack_min = first_optional[](#l31.206)
unpack_max = len(selfless)[](#l31.207)
template_dict['unpack_min'] = str(unpack_min)[](#l31.208)
template_dict['unpack_max'] = str(unpack_max)[](#l31.209)
if has_option_groups: self.render_option_group_parsing(f, template_dict)
templates = self.output_templates(f)[](#l31.214)
- for name, destination in clinic.field_destinations.items(): template = templates[name] if has_option_groups: @@ -1077,6 +1082,7 @@ methoddef_define + @contextlib.contextmanager def OverrideStdioWith(stdout): saved_stdout = sys.stdout @@ -1775,7 +1781,9 @@ unsupported_special_methods = set(""" """.strip().split()) -INVALID, CALLABLE, STATIC_METHOD, CLASS_METHOD, METHOD_INIT, METHOD_NEW = range(6) +INVALID, CALLABLE, STATIC_METHOD, CLASS_METHOD, METHOD_INIT, METHOD_NEW = """ +INVALID, CALLABLE, STATIC_METHOD, CLASS_METHOD, METHOD_INIT, METHOD_NEW +""".replace(",", "").strip().split() class Function: """ @@ -1969,6 +1977,19 @@ class CConverter(metaclass=CConverterAut # Only used by format units ending with '#'. length = False
Should we show this parameter in the generated
text_signature? This is almost always True.
- show_in_signature = True
Overrides the name used in a text signature.
The name used for a "self" parameter must be one of
self, type, or module; however users can set their own.
This lets the self_converter overrule the user-settable
name, just for the text signature.
Only set by self_converter.
- signature_name = None
def init(self, name, function, default=unspecified, *, c_default=None, py_default=None, annotation=unspecified, **kwargs): keep in sync with self_converter.init self.function = function self.name = name
@@ -1998,11 +2019,23 @@ class CConverter(metaclass=CConverterAut def is_optional(self): return (self.default is not unspecified)
- def render(self, parameter, data):
"""[](#l31.263)
parameter is a clinic.Parameter instance.[](#l31.264)
data is a CRenderData instance.[](#l31.265)
"""[](#l31.266)
- def _render_self(self, parameter, data):
self.parameter = parameter[](#l31.268)
original_name = self.name[](#l31.269)
name = ensure_legal_c_identifier(original_name)[](#l31.270)
# impl_arguments[](#l31.272)
s = ("&" if self.impl_by_reference else "") + name[](#l31.273)
data.impl_arguments.append(s)[](#l31.274)
if self.length:[](#l31.275)
data.impl_arguments.append(self.length_name())[](#l31.276)
# impl_parameters[](#l31.278)
data.impl_parameters.append(self.simple_declaration(by_reference=self.impl_by_reference))[](#l31.279)
if self.length:[](#l31.280)
data.impl_parameters.append("Py_ssize_clean_t " + self.length_name())[](#l31.281)
- def _render_non_self(self, parameter, data): self.parameter = parameter original_name = self.name name = ensure_legal_c_identifier(original_name)
@@ -2016,12 +2049,6 @@ class CConverter(metaclass=CConverterAut if initializers: data.initializers.append('/* initializers for ' + name + ' */\n' + initializers.rstrip())
# impl_arguments[](#l31.291)
s = ("&" if self.impl_by_reference else "") + name[](#l31.292)
data.impl_arguments.append(s)[](#l31.293)
if self.length:[](#l31.294)
data.impl_arguments.append(self.length_name())[](#l31.295)
- # keywords data.keywords.append(original_name) @@ -2035,16 +2062,19 @@ class CConverter(metaclass=CConverterAut # parse_arguments self.parse_argument(data.parse_arguments)
# impl_parameters[](#l31.304)
data.impl_parameters.append(self.simple_declaration(by_reference=self.impl_by_reference))[](#l31.305)
if self.length:[](#l31.306)
data.impl_parameters.append("Py_ssize_clean_t " + self.length_name())[](#l31.307)
- # cleanup cleanup = self.cleanup() if cleanup: data.cleanup.append('/* Cleanup for ' + name + ' */\n' + cleanup.rstrip() + "\n")
- def render(self, parameter, data):
"""[](#l31.315)
parameter is a clinic.Parameter instance.[](#l31.316)
data is a CRenderData instance.[](#l31.317)
"""[](#l31.318)
self._render_self(parameter, data)[](#l31.319)
self._render_non_self(parameter, data)[](#l31.320)
+ def length_name(self): """Computes the name of the associated "length" variable.""" if not self.length: @@ -2318,7 +2348,7 @@ class str_converter(CConverter): format_unit = 'et#' if format_unit.endswith('#'):
print("Warning: code using format unit ", repr(format_unit), "probably doesn't work properly.")[](#l31.329)
fail("Sorry: code using format unit ", repr(format_unit), "probably doesn't work properly yet.\nGive Larry your test case and he'll it.")[](#l31.330) # TODO set pointer to NULL[](#l31.331) # TODO add cleanup for buffer[](#l31.332) pass[](#l31.333)
@@ -2421,35 +2451,108 @@ class Py_buffer_converter(CConverter): return "".join(["if (", name, ".obj)\n PyBuffer_Release(&", name, ");\n"]) +def correct_name_for_self(f):
- if f.kind in (CALLABLE, METHOD_INIT):
if f.cls:[](#l31.340)
return "PyObject *", "self"[](#l31.341)
return "PyModuleDef *", "module"[](#l31.342)
- if f.kind == STATIC_METHOD:
return "void *", "null"[](#l31.344)
- if f.kind in (CLASS_METHOD, METHOD_NEW):
return "PyTypeObject *", "type"[](#l31.346)
- raise RuntimeError("Unhandled type of function f: " + repr(f.kind))
+ + class self_converter(CConverter): """ A special-case converter: this is the default converter used for "self". """
+ + def converter_init(self, *, type=None): f = self.function
if f.kind in (CALLABLE, METHOD_INIT):[](#l31.362)
if f.cls:[](#l31.363)
self.name = "self"[](#l31.364)
else:[](#l31.365)
self.name = "module"[](#l31.366)
self.type = "PyModuleDef *"[](#l31.367)
elif f.kind == STATIC_METHOD:[](#l31.368)
self.name = "null"[](#l31.369)
self.type = "void *"[](#l31.370)
elif f.kind == CLASS_METHOD:[](#l31.371)
self.name = "cls"[](#l31.372)
self.type = "PyTypeObject *"[](#l31.373)
elif f.kind == METHOD_NEW:[](#l31.374)
self.name = "type"[](#l31.375)
self.type = "PyTypeObject *"[](#l31.376)
if type:[](#l31.378)
self.type = type[](#l31.379)
default_type, default_name = correct_name_for_self(f)[](#l31.380)
self.signature_name = default_name[](#l31.381)
self.type = type or self.type or default_type[](#l31.382)
kind = self.function.kind[](#l31.384)
new_or_init = kind in (METHOD_NEW, METHOD_INIT)[](#l31.385)
if (kind == STATIC_METHOD) or new_or_init:[](#l31.387)
self.show_in_signature = False[](#l31.388)
tp_new (METHOD_NEW) functions are of type newfunc:
typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *);
PyTypeObject is a typedef for struct _typeobject.
- #
tp_init (METHOD_INIT) functions are of type initproc:
typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
- #
All other functions generated by Argument Clinic are stored in
PyMethodDef structures, in the ml_meth slot, which is of type PyCFunction:
typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
However! We habitually cast these functions to PyCFunction,
since functions that accept keyword arguments don't fit this signature
but are stored there anyway. So strict type equality isn't important
for these functions.
- #
So:
- #
* The name of the first parameter to the impl and the parsing function will always
be self.name.
- #
* The type of the first parameter to the impl will always be of self.type.
- #
* If the function is neither tp_new (METHOD_NEW) nor tp_init (METHOD_INIT):
* The type of the first parameter to the parsing function is also self.type.
This means that if you step into the parsing function, your "self" parameter
is of the correct type, which may make debugging more pleasant.
- #
* Else if the function is tp_new (METHOD_NEW):
* The type of the first parameter to the parsing function is "PyTypeObject *",
so the type signature of the function call is an exact match.
* If self.type != "PyTypeObject *", we cast the first parameter to self.type
in the impl call.
- #
* Else if the function is tp_init (METHOD_INIT):
* The type of the first parameter to the parsing function is "PyObject *",
so the type signature of the function call is an exact match.
* If self.type != "PyObject *", we cast the first parameter to self.type
in the impl call.
- @property
- def parser_type(self):
kind = self.function.kind[](#l31.431)
if kind == METHOD_NEW:[](#l31.432)
return "PyTypeObject *"[](#l31.433)
if kind == METHOD_INIT:[](#l31.434)
return "PyObject *"[](#l31.435)
return self.type[](#l31.436)
def render(self, parameter, data):
fail("render() should never be called on self_converter instances")[](#l31.439)
"""[](#l31.440)
parameter is a clinic.Parameter instance.[](#l31.441)
data is a CRenderData instance.[](#l31.442)
"""[](#l31.443)
if self.function.kind == STATIC_METHOD:[](#l31.444)
return[](#l31.445)
self._render_self(parameter, data)[](#l31.447)
if self.type != self.parser_type:[](#l31.449)
# insert cast to impl_argument[0], aka self.[](#l31.450)
# we know we're in the first slot in all the CRenderData lists,[](#l31.451)
# because we render parameters in order, and self is always first.[](#l31.452)
assert len(data.impl_arguments) == 1[](#l31.453)
assert data.impl_arguments[0] == self.name[](#l31.454)
data.impl_arguments[0] = '(' + self.type + ")" + data.impl_arguments[0][](#l31.455)
- def set_template_dict(self, template_dict):
template_dict['self_name'] = self.name[](#l31.458)
template_dict['self_type'] = self.parser_type[](#l31.459)
@@ -2997,7 +3100,7 @@ class DSLParser: if not return_converter: return_converter = init_return_converter() elif fields[-1] in unsupported_special_methods:
fail(fields[-1] + " should not be converted to Argument Clinic! (Yet.)")[](#l31.467)
fail(fields[-1] + " is a special method and cannot be converted to Argument Clinic! (Yet.)")[](#l31.468)
if not return_converter: return_converter = CReturnConverter() @@ -3007,6 +3110,13 @@ class DSLParser: self.function = Function(name=function_name, full_name=full_name, module=module, cls=cls, c_basename=c_basename, return_converter=return_converter, kind=self.kind, coexist=self.coexist) self.block.signatures.append(self.function) +
# insert a self converter automatically[](#l31.477)
_, name = correct_name_for_self(self.function)[](#l31.478)
sc = self.function.self_converter = self_converter(name, self.function)[](#l31.479)
p_self = Parameter(sc.name, inspect.Parameter.POSITIONAL_ONLY, function=self.function, converter=sc)[](#l31.480)
self.function.parameters[sc.name] = p_self[](#l31.481)
+ (cls or module).functions.append(self.function) self.next(self.state_parameters_start) @@ -3173,34 +3283,43 @@ class DSLParser: try: module = ast.parse(ast_input)
# blacklist of disallowed ast nodes[](#l31.490)
class DetectBadNodes(ast.NodeVisitor):[](#l31.491)
bad = False[](#l31.492)
def bad_node(self, node):[](#l31.493)
self.bad = True[](#l31.494)
# inline function call[](#l31.496)
visit_Call = bad_node[](#l31.497)
# inline if statement ("x = 3 if y else z")[](#l31.498)
visit_IfExp = bad_node[](#l31.499)
# comprehensions and generator expressions[](#l31.501)
visit_ListComp = visit_SetComp = bad_node[](#l31.502)
visit_DictComp = visit_GeneratorExp = bad_node[](#l31.503)
# literals for advanced types[](#l31.505)
visit_Dict = visit_Set = bad_node[](#l31.506)
visit_List = visit_Tuple = bad_node[](#l31.507)
# "starred": "a = [1, 2, 3]; *a"[](#l31.509)
visit_Starred = bad_node[](#l31.510)
# allow ellipsis, for now[](#l31.512)
# visit_Ellipsis = bad_node[](#l31.513)
blacklist = DetectBadNodes()[](#l31.515)
blacklist.visit(module)[](#l31.516)
if blacklist.bad:[](#l31.517)
bad = False[](#l31.518)
if 'c_default' not in kwargs:[](#l31.519)
# we can only represent very simple data values in C.[](#l31.520)
# detect whether default is okay, via a blacklist[](#l31.521)
# of disallowed ast nodes.[](#l31.522)
class DetectBadNodes(ast.NodeVisitor):[](#l31.523)
bad = False[](#l31.524)
def bad_node(self, node):[](#l31.525)
self.bad = True[](#l31.526)
# inline function call[](#l31.528)
visit_Call = bad_node[](#l31.529)
# inline if statement ("x = 3 if y else z")[](#l31.530)
visit_IfExp = bad_node[](#l31.531)
# comprehensions and generator expressions[](#l31.533)
visit_ListComp = visit_SetComp = bad_node[](#l31.534)
visit_DictComp = visit_GeneratorExp = bad_node[](#l31.535)
# literals for advanced types[](#l31.537)
visit_Dict = visit_Set = bad_node[](#l31.538)
visit_List = visit_Tuple = bad_node[](#l31.539)
# "starred": "a = [1, 2, 3]; *a"[](#l31.541)
visit_Starred = bad_node[](#l31.542)
# allow ellipsis, for now[](#l31.544)
# visit_Ellipsis = bad_node[](#l31.545)
blacklist = DetectBadNodes()[](#l31.547)
blacklist.visit(module)[](#l31.548)
bad = blacklist.bad[](#l31.549)
else:[](#l31.550)
# if they specify a c_default, we can be more lenient about the default value.[](#l31.551)
# but at least ensure that we can turn it into text and reconstitute it correctly.[](#l31.552)
bad = default != repr(eval(default))[](#l31.553)
if bad:[](#l31.554) fail("Unsupported expression as default value: " + repr(default))[](#l31.555)
expr = module.body[0].value @@ -3263,18 +3382,22 @@ class DSLParser: fail('{} is not a valid {}converter'.format(name, legacy_str)) converter = dict[name](parameter_name, self.function, value, **kwargs)
# special case: if it's the self converter,[](#l31.562)
# don't actually add it to the parameter list[](#l31.563)
kind = inspect.Parameter.KEYWORD_ONLY if self.keyword_only else inspect.Parameter.POSITIONAL_OR_KEYWORD[](#l31.564)
+ if isinstance(converter, self_converter):
if self.function.parameters or (self.parameter_state != self.ps_required):[](#l31.567)
fail("The 'self' parameter, if specified, must be the very first thing in the parameter block.")[](#l31.568)
if self.function.self_converter:[](#l31.569)
fail("You can't specify the 'self' parameter more than once.")[](#l31.570)
self.function.self_converter = converter[](#l31.571)
self.parameter_state = self.ps_start[](#l31.572)
return[](#l31.573)
kind = inspect.Parameter.KEYWORD_ONLY if self.keyword_only else inspect.Parameter.POSITIONAL_OR_KEYWORD[](#l31.575)
if len(self.function.parameters) == 1:[](#l31.576)
if (self.parameter_state != self.ps_required):[](#l31.577)
fail("A 'self' parameter cannot be marked optional.")[](#l31.578)
if value is not unspecified:[](#l31.579)
fail("A 'self' parameter cannot have a default value.")[](#l31.580)
if self.group:[](#l31.581)
fail("A 'self' parameter cannot be in an optional group.")[](#l31.582)
kind = inspect.Parameter.POSITIONAL_ONLY[](#l31.583)
self.parameter_state = self.ps_start[](#l31.584)
self.function.parameters.clear()[](#l31.585)
else:[](#l31.586)
fail("A 'self' parameter, if specified, must be the very first thing in the parameter block.")[](#l31.587)
+ p = Parameter(parameter_name, kind, function=self.function, converter=converter, default=value, group=self.group) if parameter_name in self.function.parameters: @@ -3333,7 +3456,7 @@ class DSLParser: self.parameter_state = self.ps_seen_slash # fixup preceeding parameters for p in self.function.parameters.values():
if p.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD:[](#l31.596)
if (p.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD and not isinstance(p.converter, self_converter)):[](#l31.597) fail("Function " + self.function.name + " mixes keyword-only and positional-only parameters, which is unsupported.")[](#l31.598) p.kind = inspect.Parameter.POSITIONAL_ONLY[](#l31.599)
@@ -3394,6 +3517,11 @@ class DSLParser: def format_docstring(self): f = self.function
new_or_init = f.kind in (METHOD_NEW, METHOD_INIT)[](#l31.605)
if new_or_init and not f.docstring:[](#l31.606)
# don't render a docstring at all, no signature, nothing.[](#l31.607)
return f.docstring[](#l31.608)
+ add, output = text_accumulator() parameters = list(f.parameters.values()) @@ -3401,7 +3529,7 @@ class DSLParser: ## docstring first line ##
if f.kind in (METHOD_NEW, METHOD_INIT):[](#l31.617)
if new_or_init:[](#l31.618) assert f.cls[](#l31.619) add(f.cls.name)[](#l31.620) else:[](#l31.621)
@@ -3409,17 +3537,24 @@ class DSLParser: add('(') # populate "right_bracket_count" field for every parameter
if parameters:[](#l31.626)
assert parameters, "We should always have a self parameter. " + repr(f)[](#l31.627)
assert isinstance(parameters[0].converter, self_converter)[](#l31.628)
parameters[0].right_bracket_count = 0[](#l31.629)
parameters_after_self = parameters[1:][](#l31.630)
if parameters_after_self:[](#l31.631) # for now, the only way Clinic supports positional-only parameters[](#l31.632)
# is if all of them are positional-only.[](#l31.633)
positional_only_parameters = [p.kind == inspect.Parameter.POSITIONAL_ONLY for p in parameters][](#l31.634)
if parameters[0].kind == inspect.Parameter.POSITIONAL_ONLY:[](#l31.635)
# is if all of them are positional-only...[](#l31.636)
#[](#l31.637)
# ... except for self! self is always positional-only.[](#l31.638)
positional_only_parameters = [p.kind == inspect.Parameter.POSITIONAL_ONLY for p in parameters_after_self][](#l31.640)
if parameters_after_self[0].kind == inspect.Parameter.POSITIONAL_ONLY:[](#l31.641) assert all(positional_only_parameters)[](#l31.642) for p in parameters:[](#l31.643) p.right_bracket_count = abs(p.group)[](#l31.644) else:[](#l31.645) # don't put any right brackets around non-positional-only parameters, ever.[](#l31.646)
for p in parameters:[](#l31.647)
for p in parameters_after_self:[](#l31.648) p.right_bracket_count = 0[](#l31.649)
right_bracket_count = 0 @@ -3439,6 +3574,9 @@ class DSLParser: add_comma = False for p in parameters:
if not p.converter.show_in_signature:[](#l31.656)
continue[](#l31.657)
+ assert p.name if p.is_keyword_only() and not added_star: @@ -3446,8 +3584,10 @@ class DSLParser: if add_comma: add(', ') add('*') -
a = [p.name][](#l31.667)
add_comma = True[](#l31.668)
name = p.converter.signature_name or p.name[](#l31.670)
a = [name][](#l31.671) if p.converter.is_optional():[](#l31.672) a.append('=')[](#l31.673) value = p.converter.py_default[](#l31.674)
@@ -3560,9 +3700,6 @@ class DSLParser: if not self.function: return
if not self.function.self_converter:[](#l31.679)
self.function.self_converter = self_converter("self", self.function)[](#l31.680)
- if self.keyword_only: values = self.function.parameters.values() if not values: @@ -3582,6 +3719,8 @@ class DSLParser: self.function.docstring = self.format_docstring() + +
maps strings to callables.
the callable should return an object
that implements the clinic parser
@@ -3607,6 +3746,7 @@ def main(argv): cmdline = argparse.ArgumentParser() cmdline.add_argument("-f", "--force", action='store_true') cmdline.add_argument("-o", "--output", type=str)
- cmdline.add_argument("-v", "--verbose", action='store_true') cmdline.add_argument("--converters", action='store_true') cmdline.add_argument("--make", action='store_true') cmdline.add_argument("filename", type=str, nargs="*") @@ -3680,13 +3820,15 @@ def main(argv): cmdline.print_usage() sys.exit(-1) for root, dirs, files in os.walk('.'):
for rcs_dir in ('.svn', '.git', '.hg'):[](#l31.706)
for rcs_dir in ('.svn', '.git', '.hg', 'build'):[](#l31.707) if rcs_dir in dirs:[](#l31.708) dirs.remove(rcs_dir)[](#l31.709) for filename in files:[](#l31.710)
if not filename.endswith('.c'):[](#l31.711)
if not (filename.endswith('.c') or filename.endswith('.h')):[](#l31.712) continue[](#l31.713) path = os.path.join(root, filename)[](#l31.714)
if ns.verbose:[](#l31.715)
print(path)[](#l31.716) parse_file(path, verify=not ns.force)[](#l31.717) return[](#l31.718)
@@ -3701,6 +3843,8 @@ def main(argv): sys.exit(-1) for filename in ns.filename:
if ns.verbose:[](#l31.724)
print(filename)[](#l31.725) parse_file(filename, output=ns.output, verify=not ns.force)[](#l31.726)