diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-05-16-18-56-36.bpo-36876.SMhxxD.rst b/Misc/NEWS.d/next/Core and Builtins/2019-05-16-18-56-36.bpo-36876.SMhxxD.rst new file mode 100644 index 00000000000000..4030425b56768c --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2019-05-16-18-56-36.bpo-36876.SMhxxD.rst @@ -0,0 +1 @@ +Move away from static locals. diff --git a/Modules/_asynciomodule.c b/Modules/_asynciomodule.c index f9037c279ac9c3..c1e7986c2eb1f3 100644 --- a/Modules/_asynciomodule.c +++ b/Modules/_asynciomodule.c @@ -19,6 +19,21 @@ _Py_IDENTIFIER(current_task); _Py_IDENTIFIER(get_event_loop); _Py_IDENTIFIER(send); _Py_IDENTIFIER(throw); +_Py_IDENTIFIER(get_loop); +_Py_IDENTIFIER(_loop); +_Py_IDENTIFIER(get_debug); +_Py_IDENTIFIER(PENDING); +_Py_IDENTIFIER(CANCELLED); +_Py_IDENTIFIER(FINISHED); +_Py_IDENTIFIER(_repr_info); +_Py_IDENTIFIER(call_exception_handler); +_Py_IDENTIFIER(message); +_Py_IDENTIFIER(exception); +_Py_IDENTIFIER(future); +_Py_IDENTIFIER(source_traceback); +_Py_IDENTIFIER(add); +_Py_IDENTIFIER(discard); +_Py_IDENTIFIER(task); /* State of the _asyncio module */ @@ -202,8 +217,6 @@ get_future_loop(PyObject *fut) { /* Implementation of `asyncio.futures._get_loop` */ - _Py_IDENTIFIER(get_loop); - _Py_IDENTIFIER(_loop); PyObject *getloop; if (Future_CheckExact(fut) || Task_CheckExact(fut)) { @@ -469,7 +482,6 @@ future_init(FutureObj *fut, PyObject *loop) { PyObject *res; int is_true; - _Py_IDENTIFIER(get_debug); // Same to FutureObj_clear() but not clearing fut->dict Py_CLEAR(fut->fut_loop); @@ -1255,9 +1267,6 @@ FutureObj_get_source_traceback(FutureObj *fut, void *Py_UNUSED(ignored)) static PyObject * FutureObj_get_state(FutureObj *fut, void *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(PENDING); - _Py_IDENTIFIER(CANCELLED); - _Py_IDENTIFIER(FINISHED); PyObject *ret = NULL; ENSURE_FUTURE_ALIVE(fut) @@ -1294,8 +1303,6 @@ _asyncio_Future__repr_info_impl(FutureObj *self) static PyObject * FutureObj_repr(FutureObj *fut) { - _Py_IDENTIFIER(_repr_info); - ENSURE_FUTURE_ALIVE(fut) PyObject *rinfo = _PyObject_CallMethodIdObjArgs((PyObject*)fut, @@ -1320,12 +1327,6 @@ FutureObj_repr(FutureObj *fut) static void FutureObj_finalize(FutureObj *fut) { - _Py_IDENTIFIER(call_exception_handler); - _Py_IDENTIFIER(message); - _Py_IDENTIFIER(exception); - _Py_IDENTIFIER(future); - _Py_IDENTIFIER(source_traceback); - PyObject *error_type, *error_value, *error_traceback; PyObject *context; PyObject *message = NULL; @@ -1845,8 +1846,6 @@ TaskWakeupMethWrapper_new(TaskObj *task) static int register_task(PyObject *task) { - _Py_IDENTIFIER(add); - PyObject *res = _PyObject_CallMethodIdObjArgs( all_tasks, &PyId_add, task, NULL); if (res == NULL) { @@ -1860,8 +1859,6 @@ register_task(PyObject *task) static int unregister_task(PyObject *task) { - _Py_IDENTIFIER(discard); - PyObject *res = _PyObject_CallMethodIdObjArgs( all_tasks, &PyId_discard, task, NULL); if (res == NULL) { @@ -2358,11 +2355,6 @@ _asyncio_Task_set_name(TaskObj *self, PyObject *value) static void TaskObj_finalize(TaskObj *task) { - _Py_IDENTIFIER(call_exception_handler); - _Py_IDENTIFIER(task); - _Py_IDENTIFIER(message); - _Py_IDENTIFIER(source_traceback); - PyObject *context; PyObject *message = NULL; PyObject *func; diff --git a/Modules/_bisectmodule.c b/Modules/_bisectmodule.c index 461a11f5099db3..d55408eeacffa5 100644 --- a/Modules/_bisectmodule.c +++ b/Modules/_bisectmodule.c @@ -51,7 +51,7 @@ bisect_right(PyObject *self, PyObject *args, PyObject *kw) Py_ssize_t lo = 0; Py_ssize_t hi = -1; Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + static char *kwlist[] = {"a", "x", "lo", "hi", NULL}; if (kw == NULL && PyTuple_GET_SIZE(args) == 2) { list = PyTuple_GET_ITEM(args, 0); @@ -59,7 +59,7 @@ bisect_right(PyObject *self, PyObject *args, PyObject *kw) } else { if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right", - keywords, &list, &item, &lo, &hi)) + kwlist, &list, &item, &lo, &hi)) return NULL; } index = internal_bisect_right(list, item, lo, hi); @@ -87,7 +87,7 @@ insort_right(PyObject *self, PyObject *args, PyObject *kw) Py_ssize_t lo = 0; Py_ssize_t hi = -1; Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + static char *kwlist[] = {"a", "x", "lo", "hi", NULL}; if (kw == NULL && PyTuple_GET_SIZE(args) == 2) { list = PyTuple_GET_ITEM(args, 0); @@ -95,7 +95,7 @@ insort_right(PyObject *self, PyObject *args, PyObject *kw) } else { if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right", - keywords, &list, &item, &lo, &hi)) + kwlist, &list, &item, &lo, &hi)) return NULL; } index = internal_bisect_right(list, item, lo, hi); @@ -168,7 +168,7 @@ bisect_left(PyObject *self, PyObject *args, PyObject *kw) Py_ssize_t lo = 0; Py_ssize_t hi = -1; Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + static char *kwlist[] = {"a", "x", "lo", "hi", NULL}; if (kw == NULL && PyTuple_GET_SIZE(args) == 2) { list = PyTuple_GET_ITEM(args, 0); @@ -176,7 +176,7 @@ bisect_left(PyObject *self, PyObject *args, PyObject *kw) } else { if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left", - keywords, &list, &item, &lo, &hi)) + kwlist, &list, &item, &lo, &hi)) return NULL; } index = internal_bisect_left(list, item, lo, hi); @@ -204,14 +204,14 @@ insort_left(PyObject *self, PyObject *args, PyObject *kw) Py_ssize_t lo = 0; Py_ssize_t hi = -1; Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + static char *kwlist[] = {"a", "x", "lo", "hi", NULL}; if (kw == NULL && PyTuple_GET_SIZE(args) == 2) { list = PyTuple_GET_ITEM(args, 0); item = PyTuple_GET_ITEM(args, 1); } else { if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left", - keywords, &list, &item, &lo, &hi)) + kwlist, &list, &item, &lo, &hi)) return NULL; } index = internal_bisect_left(list, item, lo, hi); diff --git a/Modules/_blake2/impl/blake2-impl.h b/Modules/_blake2/impl/blake2-impl.h index bbe3c0f1cfcfa5..4255088d1226d9 100644 --- a/Modules/_blake2/impl/blake2-impl.h +++ b/Modules/_blake2/impl/blake2-impl.h @@ -131,7 +131,7 @@ BLAKE2_LOCAL_INLINE(uint64_t) rotr64( const uint64_t w, const unsigned c ) /* prevents compiler optimizing out memset() */ BLAKE2_LOCAL_INLINE(void) secure_zero_memory(void *v, size_t n) { - static void *(*const volatile memset_v)(void *, int, size_t) = &memset; + static void *(*const volatile memset_v)(void *, int, size_t) = &memset; // Static is okay here (process-global). memset_v(v, 0, n); } diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c index a40b681d2835f5..cb6de419f4aa0e 100644 --- a/Modules/_collectionsmodule.c +++ b/Modules/_collectionsmodule.c @@ -7,6 +7,12 @@ #include /* For size_t */ #endif + +_Py_IDENTIFIER(__dict__); +_Py_IDENTIFIER(items); +_Py_IDENTIFIER(get); +_Py_IDENTIFIER(__setitem__); + /*[clinic input] class _tuplegetter "_tuplegetterobject *" "&tuplegetter_type" [clinic start generated code]*/ @@ -1321,7 +1327,6 @@ static PyObject * deque_reduce(dequeobject *deque, PyObject *Py_UNUSED(ignored)) { PyObject *dict, *it; - _Py_IDENTIFIER(__dict__); if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) { return NULL; @@ -2031,7 +2036,6 @@ defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored)) PyObject *items; PyObject *iter; PyObject *result; - _Py_IDENTIFIER(items); if (dd->default_factory == NULL || dd->default_factory == Py_None) args = PyTuple_New(0); @@ -2236,8 +2240,6 @@ Count elements in the iterable, updating the mapping"); static PyObject * _count_elements(PyObject *self, PyObject *args) { - _Py_IDENTIFIER(get); - _Py_IDENTIFIER(__setitem__); PyObject *it, *iterable, *mapping, *oldval; PyObject *newval = NULL; PyObject *key = NULL; diff --git a/Modules/_csv.c b/Modules/_csv.c index e31b158c601e86..409d0def80b80d 100644 --- a/Modules/_csv.c +++ b/Modules/_csv.c @@ -15,6 +15,8 @@ module instead. #include +_Py_IDENTIFIER(write); + typedef struct { PyObject *error_obj; /* CSV exception */ PyObject *dialects; /* Dialect registry */ @@ -1365,7 +1367,6 @@ csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args) { PyObject * output_file, * dialect = NULL; WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type); - _Py_IDENTIFIER(write); if (!self) return NULL; diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index 13cf76a16d768a..0069d76156dba6 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -116,6 +116,19 @@ bytes(cdata) #endif #include "ctypes.h" + +_Py_IDENTIFIER(_abstract_); +_Py_IDENTIFIER(_fields_); +_Py_IDENTIFIER(_as_parameter_); +_Py_IDENTIFIER(_type_); +_Py_IDENTIFIER(_length_); +_Py_IDENTIFIER(from_param); +_Py_IDENTIFIER(_flags_); +_Py_IDENTIFIER(_argtypes_); +_Py_IDENTIFIER(_restype_); +_Py_IDENTIFIER(_check_retval_); +_Py_IDENTIFIER(__ctypes_from_outparam__); + PyObject *PyExc_ArgError = NULL; /* This dict maps ctypes types to POINTER types */ @@ -441,8 +454,6 @@ StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isSt PyTypeObject *result; PyObject *fields; StgDictObject *dict; - _Py_IDENTIFIER(_abstract_); - _Py_IDENTIFIER(_fields_); /* create the new instance (which is a class, since we are a metatype!) */ @@ -721,7 +732,6 @@ static const char from_param_doc[] = static PyObject * CDataType_from_param(PyObject *type, PyObject *value) { - _Py_IDENTIFIER(_as_parameter_); PyObject *as_parameter; int res = PyObject_IsInstance(value, type); if (res == -1) @@ -992,7 +1002,6 @@ PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) StgDictObject *stgdict; PyObject *proto; PyObject *typedict; - _Py_IDENTIFIER(_type_); typedict = PyTuple_GetItem(args, 2); if (!typedict) @@ -1070,7 +1079,6 @@ static PyObject * PyCPointerType_set_type(PyTypeObject *self, PyObject *type) { StgDictObject *dict; - _Py_IDENTIFIER(_type_); dict = PyType_stgdict((PyObject *)self); if (!dict) { @@ -1427,8 +1435,6 @@ PyCArrayType_paramfunc(CDataObject *self) static PyObject * PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - _Py_IDENTIFIER(_length_); - _Py_IDENTIFIER(_type_); PyTypeObject *result; StgDictObject *stgdict; StgDictObject *itemdict; @@ -1626,7 +1632,6 @@ static const char SIMPLE_TYPE_CHARS[] = "cbBhHiIlLdfuzZqQPXOv?g"; static PyObject * c_wchar_p_from_param(PyObject *type, PyObject *value) { - _Py_IDENTIFIER(_as_parameter_); PyObject *as_parameter; int res; if (value == Py_None) { @@ -1693,7 +1698,6 @@ c_wchar_p_from_param(PyObject *type, PyObject *value) static PyObject * c_char_p_from_param(PyObject *type, PyObject *value) { - _Py_IDENTIFIER(_as_parameter_); PyObject *as_parameter; int res; if (value == Py_None) { @@ -1760,7 +1764,6 @@ c_char_p_from_param(PyObject *type, PyObject *value) static PyObject * c_void_p_from_param(PyObject *type, PyObject *value) { - _Py_IDENTIFIER(_as_parameter_); StgDictObject *stgd; PyObject *as_parameter; int res; @@ -1900,6 +1903,8 @@ static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O static PyMethodDef c_char_p_method = { "from_param", c_char_p_from_param, METH_O }; static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O }; +static PyObject *swapped_type_suffix = NULL; + static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds, PyObject *proto, struct fielddesc *fmt) { @@ -1908,25 +1913,25 @@ static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject PyObject *name = PyTuple_GET_ITEM(args, 0); PyObject *newname; PyObject *swapped_args; - static PyObject *suffix; Py_ssize_t i; swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); if (!swapped_args) return NULL; - if (suffix == NULL) + if (swapped_type_suffix == NULL) { #ifdef WORDS_BIGENDIAN - suffix = PyUnicode_InternFromString("_le"); + swapped_type_suffix = PyUnicode_InternFromString("_le"); #else - suffix = PyUnicode_InternFromString("_be"); + swapped_type_suffix = PyUnicode_InternFromString("_be"); #endif - if (suffix == NULL) { - Py_DECREF(swapped_args); - return NULL; + if (swapped_type_suffix == NULL) { + Py_DECREF(swapped_args); + return NULL; + } } - newname = PyUnicode_Concat(name, suffix); + newname = PyUnicode_Concat(name, swapped_type_suffix); if (newname == NULL) { Py_DECREF(swapped_args); return NULL; @@ -2005,7 +2010,6 @@ PyCSimpleType_paramfunc(CDataObject *self) static PyObject * PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - _Py_IDENTIFIER(_type_); PyTypeObject *result; StgDictObject *stgdict; PyObject *proto; @@ -2190,7 +2194,6 @@ PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) static PyObject * PyCSimpleType_from_param(PyObject *type, PyObject *value) { - _Py_IDENTIFIER(_as_parameter_); StgDictObject *dict; const char *fmt; PyCArgObject *parg; @@ -2311,7 +2314,6 @@ PyTypeObject PyCSimpleType_Type = { static PyObject * converters_from_argtypes(PyObject *ob) { - _Py_IDENTIFIER(from_param); PyObject *converters; Py_ssize_t i; Py_ssize_t nArgs; @@ -2359,10 +2361,6 @@ make_funcptrtype_dict(StgDictObject *stgdict) { PyObject *ob; PyObject *converters = NULL; - _Py_IDENTIFIER(_flags_); - _Py_IDENTIFIER(_argtypes_); - _Py_IDENTIFIER(_restype_); - _Py_IDENTIFIER(_check_retval_); stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; stgdict->length = 1; @@ -3164,7 +3162,6 @@ PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self, void *Py_UNUSED(ignored)) static int PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob, void *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(_check_retval_); PyObject *checker, *oldchecker; if (ob == NULL) { oldchecker = self->checker; @@ -3955,7 +3952,6 @@ _build_result(PyObject *result, PyObject *callargs, PyTuple_SET_ITEM(tup, index, v); index++; } else if (bit & outmask) { - _Py_IDENTIFIER(__ctypes_from_outparam__); v = PyTuple_GET_ITEM(callargs, i); v = _PyObject_CallMethodId(v, &PyId___ctypes_from_outparam__, NULL); @@ -4241,7 +4237,6 @@ _init_pos_args(PyObject *self, PyTypeObject *type, StgDictObject *dict; PyObject *fields; Py_ssize_t i; - _Py_IDENTIFIER(_fields_); if (PyType_stgdict((PyObject *)type->tp_base)) { index = _init_pos_args(self, type->tp_base, @@ -4731,18 +4726,19 @@ PyTypeObject PyCArray_Type = { 0, /* tp_free */ }; +static PyObject *array_type_cache; + PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length) { - static PyObject *cache; PyObject *key; PyObject *result; char name[256]; PyObject *len; - if (cache == NULL) { - cache = PyDict_New(); - if (cache == NULL) + if (array_type_cache == NULL) { + array_type_cache = PyDict_New(); + if (array_type_cache == NULL) return NULL; } len = PyLong_FromSsize_t(length); @@ -4752,7 +4748,7 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length) Py_DECREF(len); if (!key) return NULL; - result = PyDict_GetItemProxy(cache, key); + result = PyDict_GetItemProxy(array_type_cache, key); if (result) { Py_INCREF(result); Py_DECREF(key); @@ -4790,7 +4786,7 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length) Py_DECREF(key); return NULL; } - if (-1 == PyDict_SetItemProxy(cache, key, result)) { + if (-1 == PyDict_SetItemProxy(array_type_cache, key, result)) { Py_DECREF(key); Py_DECREF(result); return NULL; diff --git a/Modules/_ctypes/_ctypes_test.c b/Modules/_ctypes/_ctypes_test.c index bae4976a08d31b..ec5f349827e5c4 100644 --- a/Modules/_ctypes/_ctypes_test.c +++ b/Modules/_ctypes/_ctypes_test.c @@ -874,14 +874,15 @@ EXPORT(S8I) __stdcall s_ret_8i_func(S8I inp) { return ret_8i_func(inp); } #include #include +static IUnknown *keep_object_last_punk = NULL; + EXPORT (HRESULT) KeepObject(IUnknown *punk) { - static IUnknown *pobj; if (punk) punk->lpVtbl->AddRef(punk); - if (pobj) - pobj->lpVtbl->Release(pobj); - pobj = punk; + if (keep_object_last_punk) + keep_object_last_punk->lpVtbl->Release(keep_object_last_punk); + keep_object_last_punk = punk; return S_OK; } diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c index 9f793c2771bfb9..fe803335b21911 100644 --- a/Modules/_ctypes/callbacks.c +++ b/Modules/_ctypes/callbacks.c @@ -7,6 +7,11 @@ #endif #include "ctypes.h" + +#ifdef MS_WIN32 +_Py_IDENTIFIER(_needs_com_addref_); +#endif + /**************************************************************/ static void @@ -107,7 +112,6 @@ static void TryAddRef(StgDictObject *dict, CDataObject *obj) { IUnknown *punk; - _Py_IDENTIFIER(_needs_com_addref_); if (!_PyDict_GetItemIdWithError((PyObject *)dict, &PyId__needs_com_addref_)) { if (PyErr_Occurred()) { @@ -429,14 +433,17 @@ static void LoadPython(void) /******************************************************************/ +static PyObject *context_dll_get_cls = NULL; + long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { PyObject *mod, *func, *result; long retval; - static PyObject *context; - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); + if (context_dll_get_cls == NULL) { + context_dll_get_cls = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); + } + PyObject *context = context_dll_get_cls; mod = PyImport_ImportModuleNoBlock("ctypes"); if (!mod) { @@ -502,14 +509,17 @@ STDAPI DllGetClassObject(REFCLSID rclsid, return result; } +static PyObject *context_dll_can_unload = NULL; + long Call_CanUnloadNow(void) { PyObject *mod, *func, *result; long retval; - static PyObject *context; - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); + if (context_dll_can_unload == NULL) { + context_dll_can_unload = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); + } + PyObject *context = context_dll_can_unload; mod = PyImport_ImportModuleNoBlock("ctypes"); if (!mod) { diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c index a8ba84be4a7612..858b64b1c265d6 100644 --- a/Modules/_ctypes/callproc.c +++ b/Modules/_ctypes/callproc.c @@ -79,6 +79,11 @@ #include #endif + +_Py_IDENTIFIER(_as_parameter_); +_Py_IDENTIFIER(__new__); +_Py_IDENTIFIER(__setstate__); + #if defined(_DEBUG) || defined(__MINGW32__) /* Don't use structured exception handling on Windows if this is defined. MingW, AFAIK, doesn't support it. @@ -125,6 +130,8 @@ static void pymem_destructor(PyObject *ptr) private copies value. */ +static PyObject *error_object_name = NULL; + /* This function creates and returns a thread-local Python object that has space to store two integer error numbers; once created the Python object is @@ -135,7 +142,6 @@ _ctypes_get_errobj(int **pspace) { PyObject *dict = PyThreadState_GetDict(); PyObject *errobj; - static PyObject *error_object_name; if (dict == NULL) { PyErr_SetString(PyExc_RuntimeError, "cannot get thread state"); @@ -706,7 +712,6 @@ static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa) #endif { - _Py_IDENTIFIER(_as_parameter_); PyObject *arg; if (_PyObject_LookupAttrId(obj, &PyId__as_parameter_, &arg) < 0) { return -1; @@ -1687,8 +1692,6 @@ static PyObject * unpickle(PyObject *self, PyObject *args) { PyObject *typ, *state, *meth, *obj, *result; - _Py_IDENTIFIER(__new__); - _Py_IDENTIFIER(__setstate__); if (!PyArg_ParseTuple(args, "OO!", &typ, &PyTuple_Type, &state)) return NULL; diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c index 157c32fd90967f..5c13adc48844ab 100644 --- a/Modules/_ctypes/cfield.c +++ b/Modules/_ctypes/cfield.c @@ -1569,11 +1569,11 @@ static struct fielddesc formattable[] = { struct fielddesc * _ctypes_get_fielddesc(const char *fmt) { - static int initialized = 0; struct fielddesc *table = formattable; - if (!initialized) { - initialized = 1; + static int ctypes_fielddesc_initialized = 0; // Static is okay here (process-global). + if (!ctypes_fielddesc_initialized) { + ctypes_fielddesc_initialized = 1; #ifdef CTYPES_UNICODE if (sizeof(wchar_t) == sizeof(short)) _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; diff --git a/Modules/_ctypes/darwin/dlfcn_simple.c b/Modules/_ctypes/darwin/dlfcn_simple.c index 2b293bb8695bce..6b900b9dcbecdf 100644 --- a/Modules/_ctypes/darwin/dlfcn_simple.c +++ b/Modules/_ctypes/darwin/dlfcn_simple.c @@ -78,11 +78,12 @@ static void *dlsymIntern(void *handle, const char *symbol); static const char *error(int setget, const char *str, ...); +static int err_filled = 0; +static char errstr[ERR_STR_LEN]; + /* Set and get the error string for use by dlerror */ static const char *error(int setget, const char *str, ...) { - static char errstr[ERR_STR_LEN]; - static int err_filled = 0; const char *retval; va_list arg; if (setget == 0) @@ -213,7 +214,7 @@ static int darwin_dlclose(void *handle) /* dlsym, prepend the underscore and call dlsymIntern */ static void *darwin_dlsym(void *handle, const char *symbol) { - static char undersym[257]; /* Saves calls to malloc(3) */ + static char undersym[257]; // Static is okay here (saves calls to malloc(3)). int sym_len = strlen(symbol); void *value = NULL; char *malloc_sym = NULL; diff --git a/Modules/_ctypes/stgdict.c b/Modules/_ctypes/stgdict.c index 3f8a0316616bf3..ad03e57f791628 100644 --- a/Modules/_ctypes/stgdict.c +++ b/Modules/_ctypes/stgdict.c @@ -6,6 +6,12 @@ #endif #include "ctypes.h" + +_Py_IDENTIFIER(_anonymous_); +_Py_IDENTIFIER(_swappedbytes_); +_Py_IDENTIFIER(_use_broken_old_ctypes_structure_semantics_); +_Py_IDENTIFIER(_pack_); + /******************************************************************/ /* StdDict - a dictionary subclass, containing additional C accessible fields @@ -281,7 +287,6 @@ MakeFields(PyObject *type, CFieldObject *descr, static int MakeAnonFields(PyObject *type) { - _Py_IDENTIFIER(_anonymous_); PyObject *anon; PyObject *anon_names; Py_ssize_t i; @@ -337,9 +342,6 @@ MakeAnonFields(PyObject *type) int PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct) { - _Py_IDENTIFIER(_swappedbytes_); - _Py_IDENTIFIER(_use_broken_old_ctypes_structure_semantics_); - _Py_IDENTIFIER(_pack_); StgDictObject *stgdict, *basedict; Py_ssize_t len, offset, size, align, i; Py_ssize_t union_size, total_align; diff --git a/Modules/_cursesmodule.c b/Modules/_cursesmodule.c index 9a1d2efd256ea5..5a1c50480c0a48 100644 --- a/Modules/_cursesmodule.c +++ b/Modules/_cursesmodule.c @@ -125,6 +125,12 @@ static const char PyCursesVersion[] = "2.2"; #include #endif + +_Py_IDENTIFIER(write); +_Py_IDENTIFIER(read); +_Py_IDENTIFIER(LINES); +_Py_IDENTIFIER(COLS); + #if !defined(HAVE_NCURSES_H) && (defined(sgi) || defined(__sun) || defined(SCO5)) #define STRICT_SYSV_CURSES /* Don't use ncurses extensions */ typedef chtype attr_t; /* No attr_t type is available */ @@ -2020,7 +2026,6 @@ _curses_window_putwin(PyCursesWindowObject *self, PyObject *file) while (1) { char buf[BUFSIZ]; Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); - _Py_IDENTIFIER(write); if (n <= 0) break; @@ -2894,7 +2899,6 @@ _curses_getwin(PyObject *module, PyObject *file) PyObject *data; size_t datalen; WINDOW *win; - _Py_IDENTIFIER(read); PyObject *res = NULL; PyCursesInitialised; @@ -3701,8 +3705,6 @@ update_lines_cols(void) { PyObject *o; PyObject *m = PyImport_ImportModuleNoBlock("curses"); - _Py_IDENTIFIER(LINES); - _Py_IDENTIFIER(COLS); if (!m) return 0; @@ -4441,17 +4443,18 @@ PyMODINIT_FUNC PyInit__curses(void) { PyObject *m, *d, *v, *c_api_object; - static void *PyCurses_API[PyCurses_API_pointers]; /* Initialize object type */ if (PyType_Ready(&PyCursesWindow_Type) < 0) return NULL; /* Initialize the C API pointer array */ - PyCurses_API[0] = (void *)&PyCursesWindow_Type; - PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; - PyCurses_API[2] = (void *)func_PyCursesInitialised; - PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + void *PyCurses_API[PyCurses_API_pointers] = { + (void *)&PyCursesWindow_Type, + (void *)func_PyCursesSetupTermCalled, + (void *)func_PyCursesInitialised, + (void *)func_PyCursesInitialisedColor, + }; /* Create the module and add the functions */ m = PyModule_Create(&_cursesmodule); diff --git a/Modules/_datetimemodule.c b/Modules/_datetimemodule.c index 83e43a24395b45..cc5e09253106a7 100644 --- a/Modules/_datetimemodule.c +++ b/Modules/_datetimemodule.c @@ -17,6 +17,17 @@ # include /* struct timeval */ #endif + +_Py_IDENTIFIER(replace); +_Py_IDENTIFIER(tzname); +_Py_IDENTIFIER(time); +_Py_IDENTIFIER(struct_time); +_Py_IDENTIFIER(fromtimestamp); +_Py_IDENTIFIER(timetuple); +_Py_IDENTIFIER(__getinitargs__); +_Py_IDENTIFIER(__getstate__); +_Py_IDENTIFIER(_strptime_datetime); + #define PyDate_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateType) #define PyDate_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DateType) @@ -1228,7 +1239,6 @@ static PyObject * call_tzname(PyObject *tzinfo, PyObject *tzinfoarg) { PyObject *result; - _Py_IDENTIFIER(tzname); assert(tzinfo != NULL); assert(check_tzinfo_subclass(tzinfo) >= 0); @@ -1336,10 +1346,10 @@ tzinfo_from_isoformat_results(int rv, int tzoffset, int tz_useconds) static PyObject * format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds) { - static const char * const DayNames[] = { + static const char * const DayNames[] = { // Static is okay here (immutable data). "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }; - static const char * const MonthNames[] = { + static const char * const MonthNames[] = { // Static is okay here (immutable data). "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; @@ -1418,7 +1428,6 @@ make_Zreplacement(PyObject *object, PyObject *tzinfoarg) PyObject *temp; PyObject *tzinfo = get_tzinfo_member(object); PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0); - _Py_IDENTIFIER(replace); if (Zreplacement == NULL) return NULL; @@ -1657,7 +1666,6 @@ time_time(void) PyObject *time = PyImport_ImportModuleNoBlock("time"); if (time != NULL) { - _Py_IDENTIFIER(time); result = _PyObject_CallMethodId(time, &PyId_time, NULL); Py_DECREF(time); @@ -1673,7 +1681,6 @@ build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag) { PyObject *time; PyObject *result; - _Py_IDENTIFIER(struct_time); PyObject *args; @@ -2432,13 +2439,13 @@ delta_new(PyTypeObject *type, PyObject *args, PyObject *kw) PyObject *y = NULL; /* temp sum of microseconds */ double leftover_us = 0.0; - static char *keywords[] = { + static char *kwlist[] = { "days", "seconds", "microseconds", "milliseconds", "minutes", "hours", "weeks", NULL }; if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", - keywords, + kwlist, &day, &second, &us, &ms, &minute, &hour, &week) == 0) goto Done; @@ -2883,7 +2890,6 @@ date_today(PyObject *cls, PyObject *dummy) { PyObject *time; PyObject *result; - _Py_IDENTIFIER(fromtimestamp); time = time_time(); if (time == NULL) @@ -3007,13 +3013,13 @@ date_fromisoformat(PyObject *cls, PyObject *dtstr) static PyObject * date_fromisocalendar(PyObject *cls, PyObject *args, PyObject *kw) { - static char *keywords[] = { + static char *kwlist[] = { "year", "week", "day", NULL }; int year, week, day; if (PyArg_ParseTupleAndKeywords(args, kw, "iii:fromisocalendar", - keywords, + kwlist, &year, &week, &day) == 0) { if (PyErr_ExceptionMatches(PyExc_OverflowError)) { PyErr_Format(PyExc_ValueError, @@ -3182,10 +3188,9 @@ date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw) PyObject *result; PyObject *tuple; PyObject *format; - _Py_IDENTIFIER(timetuple); - static char *keywords[] = {"format", NULL}; + static char *kwlist[] = {"format", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, + if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", kwlist, &format)) return NULL; @@ -3603,8 +3608,6 @@ tzinfo_reduce(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *args, *state; PyObject *getinitargs, *getstate; - _Py_IDENTIFIER(__getinitargs__); - _Py_IDENTIFIER(__getstate__); getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__); if (getinitargs != NULL) { @@ -4184,10 +4187,10 @@ time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw) { char buf[100]; char *timespec = NULL; - static char *keywords[] = {"timespec", NULL}; + static char *kwlist[] = {"timespec", NULL}; PyObject *result; int us = TIME_GET_MICROSECOND(self); - static char *specs[][2] = { + static const char *specs[5][2] = { // Static is okay here (immutable data). {"hours", "%02d"}, {"minutes", "%02d:%02d"}, {"seconds", "%02d:%02d:%02d"}, @@ -4196,7 +4199,7 @@ time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw) }; size_t given_spec; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, ×pec)) + if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", kwlist, ×pec)) return NULL; if (timespec == NULL || strcmp(timespec, "auto") == 0) { @@ -4250,9 +4253,9 @@ time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw) PyObject *result; PyObject *tuple; PyObject *format; - static char *keywords[] = {"format", NULL}; + static char *kwlist[] = {"format", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, + if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", kwlist, &format)) return NULL; @@ -4984,10 +4987,10 @@ datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw) PyObject *self; PyObject *timestamp; PyObject *tzinfo = Py_None; - static char *keywords[] = {"timestamp", "tz", NULL}; + static char *kwlist[] = {"timestamp", "tz", NULL}; if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp", - keywords, ×tamp, &tzinfo)) + kwlist, ×tamp, &tzinfo)) return NULL; if (check_tzinfo_subclass(tzinfo) < 0) return NULL; @@ -5017,23 +5020,23 @@ datetime_utcfromtimestamp(PyObject *cls, PyObject *args) return result; } +static PyObject *cached__strptime = NULL; + /* Return new datetime from _strptime.strptime_datetime(). */ static PyObject * datetime_strptime(PyObject *cls, PyObject *args) { - static PyObject *module = NULL; PyObject *string, *format; - _Py_IDENTIFIER(_strptime_datetime); if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format)) return NULL; - if (module == NULL) { - module = PyImport_ImportModuleNoBlock("_strptime"); - if (module == NULL) + if (cached__strptime == NULL) { + cached__strptime = PyImport_ImportModuleNoBlock("_strptime"); + if (cached__strptime == NULL) return NULL; } - return _PyObject_CallMethodIdObjArgs(module, &PyId__strptime_datetime, + return _PyObject_CallMethodIdObjArgs(cached__strptime, &PyId__strptime_datetime, cls, string, format, NULL); } @@ -5041,13 +5044,13 @@ datetime_strptime(PyObject *cls, PyObject *args) static PyObject * datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) { - static char *keywords[] = {"date", "time", "tzinfo", NULL}; + static char *kwlist[] = {"date", "time", "tzinfo", NULL}; PyObject *date; PyObject *time; PyObject *tzinfo = NULL; PyObject *result = NULL; - if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords, + if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", kwlist, &PyDateTime_DateType, &date, &PyDateTime_TimeType, &time, &tzinfo)) { if (tzinfo == NULL) { @@ -5415,11 +5418,11 @@ datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { int sep = 'T'; char *timespec = NULL; - static char *keywords[] = {"sep", "timespec", NULL}; + static char *kwlist[] = {"sep", "timespec", NULL}; char buffer[100]; PyObject *result = NULL; int us = DATE_GET_MICROSECOND(self); - static char *specs[][2] = { + static const char *specs[5][2] = { // Static is okay here (immutable data). {"hours", "%04d-%02d-%02d%c%02d"}, {"minutes", "%04d-%02d-%02d%c%02d:%02d"}, {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"}, @@ -5428,7 +5431,7 @@ datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) }; size_t given_spec; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, ×pec)) + if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", kwlist, &sep, ×pec)) return NULL; if (timespec == NULL || strcmp(timespec, "auto") == 0) { @@ -5871,9 +5874,9 @@ datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) PyObject *temp; PyObject *self_tzinfo; PyObject *tzinfo = Py_None; - static char *keywords[] = {"tz", NULL}; + static char *kwlist[] = {"tz", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords, + if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", kwlist, &tzinfo)) return NULL; diff --git a/Modules/_dbmmodule.c b/Modules/_dbmmodule.c index 21784ae2ce4fd2..6f78ba3e6b616a 100644 --- a/Modules/_dbmmodule.c +++ b/Modules/_dbmmodule.c @@ -28,6 +28,9 @@ static const char which_dbm[] = "Berkeley DB"; #error "No ndbm.h available!" #endif + +_Py_IDENTIFIER(close); + /*[clinic input] module _dbm class _dbm.dbm "dbmobject *" "&Dbmtype" @@ -369,7 +372,6 @@ dbm__enter__(PyObject *self, PyObject *args) static PyObject * dbm__exit__(PyObject *self, PyObject *args) { - _Py_IDENTIFIER(close); return _PyObject_CallMethodId(self, &PyId_close, NULL); } diff --git a/Modules/_decimal/libmpdec/context.c b/Modules/_decimal/libmpdec/context.c index 24c7b890c1d989..2faf67a9f3de74 100644 --- a/Modules/_decimal/libmpdec/context.c +++ b/Modules/_decimal/libmpdec/context.c @@ -48,7 +48,7 @@ void (* mpd_traphandler)(mpd_context_t *) = mpd_dflt_traphandler; void mpd_setminalloc(mpd_ssize_t n) { - static int minalloc_is_set = 0; + static int minalloc_is_set = 0; // Static is okay here (process-global). if (minalloc_is_set) { mpd_err_warn("mpd_setminalloc: ignoring request to set " diff --git a/Modules/_elementtree.c b/Modules/_elementtree.c index f5fc4437deb554..e8d69f84a13143 100644 --- a/Modules/_elementtree.c +++ b/Modules/_elementtree.c @@ -16,6 +16,16 @@ #include "Python.h" #include "structmember.h" + +_Py_IDENTIFIER(find); +_Py_IDENTIFIER(findtext); +_Py_IDENTIFIER(findall); +_Py_IDENTIFIER(iterfind); +_Py_IDENTIFIER(text); +_Py_IDENTIFIER(tail); +_Py_IDENTIFIER(append); +_Py_IDENTIFIER(doctype); + /* -------------------------------------------------------------------- */ /* configuration */ @@ -1246,7 +1256,6 @@ _elementtree_Element_find_impl(ElementObject *self, PyObject *path, elementtreestate *st = ET_STATE_GLOBAL; if (checkpath(path) || namespaces != Py_None) { - _Py_IDENTIFIER(find); return _PyObject_CallMethodIdObjArgs( st->elementpath_obj, &PyId_find, self, path, namespaces, NULL ); @@ -1287,7 +1296,6 @@ _elementtree_Element_findtext_impl(ElementObject *self, PyObject *path, /*[clinic end generated code: output=83b3ba4535d308d2 input=b53a85aa5aa2a916]*/ { Py_ssize_t i; - _Py_IDENTIFIER(findtext); elementtreestate *st = ET_STATE_GLOBAL; if (checkpath(path) || namespaces != Py_None) @@ -1344,7 +1352,6 @@ _elementtree_Element_findall_impl(ElementObject *self, PyObject *path, elementtreestate *st = ET_STATE_GLOBAL; if (checkpath(path) || namespaces != Py_None) { - _Py_IDENTIFIER(findall); return _PyObject_CallMethodIdObjArgs( st->elementpath_obj, &PyId_findall, self, path, namespaces, NULL ); @@ -1388,7 +1395,6 @@ _elementtree_Element_iterfind_impl(ElementObject *self, PyObject *path, /*[clinic end generated code: output=ecdd56d63b19d40f input=abb974e350fb65c7]*/ { PyObject* tag = path; - _Py_IDENTIFIER(iterfind); elementtreestate *st = ET_STATE_GLOBAL; return _PyObject_CallMethodIdObjArgs( @@ -2654,13 +2660,11 @@ treebuilder_flush_data(TreeBuilderObject* self) } if (self->this == element) { - _Py_IDENTIFIER(text); return treebuilder_set_element_text_or_tail( element, &self->data, &((ElementObject *) element)->text, &PyId_text); } else { - _Py_IDENTIFIER(tail); return treebuilder_set_element_text_or_tail( element, &self->data, &((ElementObject *) element)->tail, &PyId_tail); @@ -2670,7 +2674,6 @@ treebuilder_flush_data(TreeBuilderObject* self) static int treebuilder_add_subelement(PyObject *element, PyObject *child) { - _Py_IDENTIFIER(append); if (Element_CheckExact(element)) { ElementObject *elem = (ElementObject *) element; return element_add_subelement(elem, child); @@ -3527,7 +3530,6 @@ expat_start_doctype_handler(XMLParserObject *self, const XML_Char *pubid, int has_internal_subset) { - _Py_IDENTIFIER(doctype); PyObject *doctype_name_obj, *sysid_obj, *pubid_obj; PyObject *res; diff --git a/Modules/_functoolsmodule.c b/Modules/_functoolsmodule.c index dcc9129fc6b183..f0e45ce043c9e6 100644 --- a/Modules/_functoolsmodule.c +++ b/Modules/_functoolsmodule.c @@ -510,9 +510,9 @@ keyobject_call(keyobject *ko, PyObject *args, PyObject *kwds) { PyObject *object; keyobject *result; - static char *kwargs[] = {"obj", NULL}; + static char *kwlist[] = {"obj", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:K", kwargs, &object)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:K", kwlist, &object)) return NULL; result = PyObject_New(keyobject, &keyobject_type); if (!result) @@ -566,10 +566,10 @@ static PyObject * functools_cmp_to_key(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *cmp; - static char *kwargs[] = {"mycmp", NULL}; + static char *kwlist[] = {"mycmp", NULL}; keyobject *object; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:cmp_to_key", kwargs, &cmp)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:cmp_to_key", kwlist, &cmp)) return NULL; object = PyObject_New(keyobject, &keyobject_type); if (!object) @@ -1096,10 +1096,10 @@ lru_cache_new(PyTypeObject *type, PyObject *args, PyObject *kw) lru_cache_object *obj; Py_ssize_t maxsize; PyObject *(*wrapper)(lru_cache_object *, PyObject *, PyObject *); - static char *keywords[] = {"user_function", "maxsize", "typed", - "cache_info_type", NULL}; + static char *kwlist[] = {"user_function", "maxsize", "typed", + "cache_info_type", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kw, "OOpO:lru_cache", keywords, + if (!PyArg_ParseTupleAndKeywords(args, kw, "OOpO:lru_cache", kwlist, &func, &maxsize_O, &typed, &cache_info_type)) { return NULL; diff --git a/Modules/_gdbmmodule.c b/Modules/_gdbmmodule.c index adf2a5865bfb81..6c2952266eb40b 100644 --- a/Modules/_gdbmmodule.c +++ b/Modules/_gdbmmodule.c @@ -16,6 +16,9 @@ extern const char * gdbm_strerror(gdbm_error); #endif + +_Py_IDENTIFIER(close); + /*[clinic input] module _gdbm class _gdbm.gdbm "dbmobject *" "&Dbmtype" @@ -496,7 +499,6 @@ dbm__enter__(PyObject *self, PyObject *args) static PyObject * dbm__exit__(PyObject *self, PyObject *args) { - _Py_IDENTIFIER(close); return _PyObject_CallMethodId(self, &PyId_close, NULL); } diff --git a/Modules/_io/_iomodule.c b/Modules/_io/_iomodule.c index 590d6ce9f1e52e..bc8082709bca2a 100644 --- a/Modules/_io/_iomodule.c +++ b/Modules/_io/_iomodule.c @@ -25,6 +25,12 @@ #include #endif + +_Py_IDENTIFIER(_blksize); +_Py_IDENTIFIER(isatty); +_Py_IDENTIFIER(mode); +_Py_IDENTIFIER(close); + /* Various interned strings */ PyObject *_PyIO_str_close = NULL; @@ -246,11 +252,6 @@ _io_open_impl(PyObject *module, PyObject *file, const char *mode, PyObject *raw, *modeobj = NULL, *buffer, *wrapper, *result = NULL, *path_or_fd = NULL; - _Py_IDENTIFIER(_blksize); - _Py_IDENTIFIER(isatty); - _Py_IDENTIFIER(mode); - _Py_IDENTIFIER(close); - is_number = PyNumber_Check(file); if (is_number) { diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c index 6f855b9edd0842..fb87a4f935202e 100644 --- a/Modules/_io/bufferedio.c +++ b/Modules/_io/bufferedio.c @@ -756,6 +756,8 @@ _buffered_init(buffered *self) return 0; } +static PyObject *cached_eintr_int = NULL; + /* Return 1 if an OSError with errno == EINTR is set (and then clears the error indicator), 0 otherwise. Should only be called when PyErr_Occurred() is true. @@ -763,13 +765,12 @@ _buffered_init(buffered *self) int _PyIO_trap_eintr(void) { - static PyObject *eintr_int = NULL; PyObject *typ, *val, *tb; PyOSErrorObject *env_err; - if (eintr_int == NULL) { - eintr_int = PyLong_FromLong(EINTR); - assert(eintr_int != NULL); + if (cached_eintr_int == NULL) { + cached_eintr_int = PyLong_FromLong(EINTR); + assert(cached_eintr_int != NULL); } if (!PyErr_ExceptionMatches(PyExc_OSError)) return 0; @@ -778,7 +779,7 @@ _PyIO_trap_eintr(void) env_err = (PyOSErrorObject *) val; assert(env_err != NULL); if (env_err->myerrno != NULL && - PyObject_RichCompareBool(env_err->myerrno, eintr_int, Py_EQ) > 0) { + PyObject_RichCompareBool(env_err->myerrno, cached_eintr_int, Py_EQ) > 0) { Py_DECREF(typ); Py_DECREF(val); Py_XDECREF(tb); diff --git a/Modules/_io/fileio.c b/Modules/_io/fileio.c index c502c430134ef6..674794cebf2193 100644 --- a/Modules/_io/fileio.c +++ b/Modules/_io/fileio.c @@ -47,6 +47,9 @@ #define SMALLCHUNK BUFSIZ #endif + +_Py_IDENTIFIER(close); + /*[clinic input] module _io class _io.FileIO "fileio *" "&PyFileIO_Type" @@ -144,7 +147,6 @@ _io_FileIO_close_impl(fileio *self) PyObject *res; PyObject *exc, *val, *tb; int rc; - _Py_IDENTIFIER(close); res = _PyObject_CallMethodIdObjArgs((PyObject*)&PyRawIOBase_Type, &PyId_close, self, NULL); if (!self->closefd) { diff --git a/Modules/_io/iobase.c b/Modules/_io/iobase.c index 6a0d9bec5af320..0f2bb4484d1c8b 100644 --- a/Modules/_io/iobase.c +++ b/Modules/_io/iobase.c @@ -14,6 +14,12 @@ #include "structmember.h" #include "_iomodule.h" + +_Py_IDENTIFIER(seek); +_Py_IDENTIFIER(_finalizing); +_Py_IDENTIFIER(extend); +_Py_IDENTIFIER(readall); + /*[clinic input] module _io class _io._IOBase "PyObject *" "&PyIOBase_Type" @@ -113,7 +119,6 @@ static PyObject * _io__IOBase_tell_impl(PyObject *self) /*[clinic end generated code: output=89a1c0807935abe2 input=04e615fec128801f]*/ { - _Py_IDENTIFIER(seek); return _PyObject_CallMethodId(self, &PyId_seek, "ii", 0, 1); } @@ -259,7 +264,6 @@ iobase_finalize(PyObject *self) PyObject *res; PyObject *error_type, *error_value, *error_traceback; int closed; - _Py_IDENTIFIER(_finalizing); /* Save the current exception, if any. */ PyErr_Fetch(&error_type, &error_value, &error_traceback); @@ -697,7 +701,6 @@ _io__IOBase_readlines_impl(PyObject *self, Py_ssize_t hint) /* XXX special-casing this made sense in the Python version in order to remove the bytecode interpretation overhead, but it could probably be removed here. */ - _Py_IDENTIFIER(extend); PyObject *ret = _PyObject_CallMethodIdObjArgs(result, &PyId_extend, self, NULL); @@ -919,7 +922,6 @@ _io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n) PyObject *b, *res; if (n < 0) { - _Py_IDENTIFIER(readall); return _PyObject_CallMethodId(self, &PyId_readall, NULL); } diff --git a/Modules/_io/winconsoleio.c b/Modules/_io/winconsoleio.c index 70a723ed746a75..6e96b400e0f923 100644 --- a/Modules/_io/winconsoleio.c +++ b/Modules/_io/winconsoleio.c @@ -27,6 +27,9 @@ #include "_iomodule.h" + +_Py_IDENTIFIER(close); + /* BUFSIZ determines how many characters can be typed at the console before it starts blocking. */ #if BUFSIZ < (16*1024) @@ -203,7 +206,6 @@ _io__WindowsConsoleIO_close_impl(winconsoleio *self) PyObject *res; PyObject *exc, *val, *tb; int rc; - _Py_IDENTIFIER(close); res = _PyObject_CallMethodIdObjArgs((PyObject*)&PyRawIOBase_Type, &PyId_close, self, NULL); if (!self->closehandle) { diff --git a/Modules/_json.c b/Modules/_json.c index 4faa9cc22edf01..170e6dd10f4ddb 100644 --- a/Modules/_json.c +++ b/Modules/_json.c @@ -73,17 +73,18 @@ static PyMemberDef encoder_members[] = { {NULL} }; +static PyObject *cached_temp_sep = NULL; + static PyObject * join_list_unicode(PyObject *lst) { /* return u''.join(lst) */ - static PyObject *sep = NULL; - if (sep == NULL) { - sep = PyUnicode_FromStringAndSize("", 0); - if (sep == NULL) + if (cached_temp_sep == NULL) { + cached_temp_sep = PyUnicode_FromStringAndSize("", 0); + if (cached_temp_sep == NULL) return NULL; } - return PyUnicode_Join(sep, lst); + return PyUnicode_Join(cached_temp_sep, lst); } /* Forward decls */ @@ -326,11 +327,12 @@ escape_unicode(PyObject *pystr) return rval; } +static PyObject *JSONDecodeError = NULL; + static void raise_errmsg(const char *msg, PyObject *s, Py_ssize_t end) { /* Use JSONDecodeError exception to raise a nice looking ValueError subclass */ - static PyObject *JSONDecodeError = NULL; PyObject *exc; if (JSONDecodeError == NULL) { PyObject *decoder = PyImport_ImportModule("json.decoder"); @@ -1371,33 +1373,34 @@ encoder_call(PyObject *self, PyObject *args, PyObject *kwds) return _PyAccu_FinishAsList(&acc); } +static PyObject *cached_str_null = NULL; +static PyObject *cached_str_true = NULL; +static PyObject *cached_str_false = NULL; + static PyObject * _encoded_const(PyObject *obj) { /* Return the JSON string representation of None, True, False */ if (obj == Py_None) { - static PyObject *s_null = NULL; - if (s_null == NULL) { - s_null = PyUnicode_InternFromString("null"); + if (cached_str_null == NULL) { + cached_str_null = PyUnicode_InternFromString("null"); } - Py_XINCREF(s_null); - return s_null; + Py_XINCREF(cached_str_null); + return cached_str_null; } else if (obj == Py_True) { - static PyObject *s_true = NULL; - if (s_true == NULL) { - s_true = PyUnicode_InternFromString("true"); + if (cached_str_true == NULL) { + cached_str_true = PyUnicode_InternFromString("true"); } - Py_XINCREF(s_true); - return s_true; + Py_XINCREF(cached_str_true); + return cached_str_true; } else if (obj == Py_False) { - static PyObject *s_false = NULL; - if (s_false == NULL) { - s_false = PyUnicode_InternFromString("false"); + if (cached_str_false == NULL) { + cached_str_false = PyUnicode_InternFromString("false"); } - Py_XINCREF(s_false); - return s_false; + Py_XINCREF(cached_str_false); + return cached_str_false; } else { PyErr_SetString(PyExc_ValueError, "not a const"); @@ -1556,14 +1559,15 @@ encoder_listencode_obj(PyEncoderObject *s, _PyAccu *acc, } } +static PyObject *cached_str_open_dict = NULL; +static PyObject *cached_str_close_dict = NULL; +static PyObject *cached_str_empty_dict = NULL; + static int encoder_listencode_dict(PyEncoderObject *s, _PyAccu *acc, PyObject *dct, Py_ssize_t indent_level) { /* Encode Python dict dct a JSON term */ - static PyObject *open_dict = NULL; - static PyObject *close_dict = NULL; - static PyObject *empty_dict = NULL; PyObject *kstr = NULL; PyObject *ident = NULL; PyObject *it = NULL; @@ -1571,13 +1575,19 @@ encoder_listencode_dict(PyEncoderObject *s, _PyAccu *acc, PyObject *item = NULL; Py_ssize_t idx; - if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) { - open_dict = PyUnicode_InternFromString("{"); - close_dict = PyUnicode_InternFromString("}"); - empty_dict = PyUnicode_InternFromString("{}"); - if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) + if (cached_str_open_dict == NULL || cached_str_close_dict == NULL || + cached_str_empty_dict == NULL) { + cached_str_open_dict = PyUnicode_InternFromString("{"); + cached_str_close_dict = PyUnicode_InternFromString("}"); + cached_str_empty_dict = PyUnicode_InternFromString("{}"); + if (cached_str_open_dict == NULL || cached_str_close_dict == NULL || + cached_str_empty_dict == NULL) { return -1; + } } + PyObject *open_dict = cached_str_open_dict; + PyObject *close_dict = cached_str_close_dict; + PyObject *empty_dict = cached_str_empty_dict; if (PyDict_GET_SIZE(dct) == 0) /* Fast path */ return _PyAccu_Accumulate(acc, empty_dict); @@ -1713,25 +1723,32 @@ encoder_listencode_dict(PyEncoderObject *s, _PyAccu *acc, } +static PyObject *cached_str_open_array = NULL; +static PyObject *cached_str_close_array = NULL; +static PyObject *cached_str_empty_array = NULL; + static int encoder_listencode_list(PyEncoderObject *s, _PyAccu *acc, PyObject *seq, Py_ssize_t indent_level) { /* Encode Python list seq to a JSON term */ - static PyObject *open_array = NULL; - static PyObject *close_array = NULL; - static PyObject *empty_array = NULL; PyObject *ident = NULL; PyObject *s_fast = NULL; Py_ssize_t i; - if (open_array == NULL || close_array == NULL || empty_array == NULL) { - open_array = PyUnicode_InternFromString("["); - close_array = PyUnicode_InternFromString("]"); - empty_array = PyUnicode_InternFromString("[]"); - if (open_array == NULL || close_array == NULL || empty_array == NULL) + if (cached_str_open_array == NULL || cached_str_close_array == NULL || + cached_str_empty_array == NULL) { + cached_str_open_array = PyUnicode_InternFromString("["); + cached_str_close_array = PyUnicode_InternFromString("]"); + cached_str_empty_array = PyUnicode_InternFromString("[]"); + if (cached_str_open_array == NULL || cached_str_close_array == NULL || + cached_str_empty_array == NULL) { return -1; + } } + PyObject *open_array = cached_str_open_array; + PyObject *close_array = cached_str_close_array; + PyObject *empty_array = cached_str_empty_array; ident = NULL; s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence"); if (s_fast == NULL) diff --git a/Modules/_lzmamodule.c b/Modules/_lzmamodule.c index 18bc3dc296e00b..27204deb4ffa87 100644 --- a/Modules/_lzmamodule.c +++ b/Modules/_lzmamodule.c @@ -189,8 +189,8 @@ INT_TYPE_CONVERTER_FUNC(lzma_match_finder, lzma_mf_converter) static void * parse_filter_spec_lzma(PyObject *spec) { - static char *optnames[] = {"id", "preset", "dict_size", "lc", "lp", - "pb", "mode", "nice_len", "mf", "depth", NULL}; + static char *kwlist[] = {"id", "preset", "dict_size", "lc", "lp", + "pb", "mode", "nice_len", "mf", "depth", NULL}; PyObject *id; PyObject *preset_obj; uint32_t preset = LZMA_PRESET_DEFAULT; @@ -224,7 +224,7 @@ parse_filter_spec_lzma(PyObject *spec) } if (!PyArg_ParseTupleAndKeywords(empty_tuple, spec, - "|OOO&O&O&O&O&O&O&O&", optnames, + "|OOO&O&O&O&O&O&O&O&", kwlist, &id, &preset_obj, uint32_converter, &options->dict_size, uint32_converter, &options->lc, @@ -245,12 +245,12 @@ parse_filter_spec_lzma(PyObject *spec) static void * parse_filter_spec_delta(PyObject *spec) { - static char *optnames[] = {"id", "dist", NULL}; + static char *kwlist[] = {"id", "dist", NULL}; PyObject *id; uint32_t dist = 1; lzma_options_delta *options; - if (!PyArg_ParseTupleAndKeywords(empty_tuple, spec, "|OO&", optnames, + if (!PyArg_ParseTupleAndKeywords(empty_tuple, spec, "|OO&", kwlist, &id, uint32_converter, &dist)) { PyErr_SetString(PyExc_ValueError, "Invalid filter specifier for delta filter"); @@ -269,12 +269,12 @@ parse_filter_spec_delta(PyObject *spec) static void * parse_filter_spec_bcj(PyObject *spec) { - static char *optnames[] = {"id", "start_offset", NULL}; + static char *kwlist[] = {"id", "start_offset", NULL}; PyObject *id; uint32_t start_offset = 0; lzma_options_bcj *options; - if (!PyArg_ParseTupleAndKeywords(empty_tuple, spec, "|OO&", optnames, + if (!PyArg_ParseTupleAndKeywords(empty_tuple, spec, "|OO&", kwlist, &id, uint32_converter, &start_offset)) { PyErr_SetString(PyExc_ValueError, "Invalid filter specifier for BCJ filter"); @@ -395,6 +395,14 @@ spec_add_field(PyObject *spec, _Py_Identifier *key, unsigned long long value) return status; } +_Py_IDENTIFIER(id); +_Py_IDENTIFIER(lc); +_Py_IDENTIFIER(lp); +_Py_IDENTIFIER(pb); +_Py_IDENTIFIER(dict_size); +_Py_IDENTIFIER(dist); +_Py_IDENTIFIER(start_offset); + static PyObject * build_filter_spec(const lzma_filter *f) { @@ -406,7 +414,6 @@ build_filter_spec(const lzma_filter *f) #define ADD_FIELD(SOURCE, FIELD) \ do { \ - _Py_IDENTIFIER(FIELD); \ if (spec_add_field(spec, &PyId_##FIELD, SOURCE->FIELD) == -1) \ goto error;\ } while (0) @@ -704,7 +711,7 @@ For one-shot compression, use the compress() function instead. static int Compressor_init(Compressor *self, PyObject *args, PyObject *kwargs) { - static char *arg_names[] = {"format", "check", "preset", "filters", NULL}; + static char *kwlist[] = {"format", "check", "preset", "filters", NULL}; int format = FORMAT_XZ; int check = -1; uint32_t preset = LZMA_PRESET_DEFAULT; @@ -712,7 +719,7 @@ Compressor_init(Compressor *self, PyObject *args, PyObject *kwargs) PyObject *filterspecs = Py_None; if (!PyArg_ParseTupleAndKeywords(args, kwargs, - "|iiOO:LZMACompressor", arg_names, + "|iiOO:LZMACompressor", kwlist, &format, &check, &preset_obj, &filterspecs)) return -1; diff --git a/Modules/_operator.c b/Modules/_operator.c index d291ec1f920ed1..807c054aa19928 100644 --- a/Modules/_operator.c +++ b/Modules/_operator.c @@ -3,6 +3,9 @@ #include "clinic/_operator.c.h" + +_Py_IDENTIFIER(partial); + /*[clinic input] module _operator [clinic start generated code]*/ @@ -1671,7 +1674,6 @@ methodcaller_reduce(methodcallerobject *mc, PyObject *Py_UNUSED(ignored)) PyObject *constructor; PyObject *newargs[2]; - _Py_IDENTIFIER(partial); functools = PyImport_ImportModule("functools"); if (!functools) return NULL; diff --git a/Modules/_pickle.c b/Modules/_pickle.c index 87f3cf7b614aab..fb08e5e934ceaf 100644 --- a/Modules/_pickle.c +++ b/Modules/_pickle.c @@ -11,6 +11,38 @@ #include "Python.h" #include "structmember.h" + +_Py_IDENTIFIER(__class__); +_Py_IDENTIFIER(__dict__); +_Py_IDENTIFIER(__getinitargs__); +_Py_IDENTIFIER(__main__); +_Py_IDENTIFIER(__module__); +_Py_IDENTIFIER(__name__); +_Py_IDENTIFIER(__newobj__); +_Py_IDENTIFIER(__newobj_ex__); +_Py_IDENTIFIER(__new__); +_Py_IDENTIFIER(__qualname__); +_Py_IDENTIFIER(__reduce__); +_Py_IDENTIFIER(__reduce_ex__); +_Py_IDENTIFIER(__setstate__); +_Py_IDENTIFIER(add); +_Py_IDENTIFIER(append); +_Py_IDENTIFIER(dispatch_table); +_Py_IDENTIFIER(extend); +_Py_IDENTIFIER(find_class); +_Py_IDENTIFIER(getattr); +_Py_IDENTIFIER(items); +_Py_IDENTIFIER(latin1); +_Py_IDENTIFIER(modules); +_Py_IDENTIFIER(peek); +_Py_IDENTIFIER(read); +_Py_IDENTIFIER(readline); +_Py_IDENTIFIER(reducer_override); +_Py_IDENTIFIER(persistent_id); +_Py_IDENTIFIER(persistent_load); +_Py_IDENTIFIER(write); + + PyDoc_STRVAR(pickle_module_doc, "Optimized C implementation for the Python pickle module."); @@ -216,7 +248,6 @@ _Pickle_InitState(PickleState *st) PyObject *compat_pickle = NULL; PyObject *codecs = NULL; PyObject *functools = NULL; - _Py_IDENTIFIER(getattr); st->getattr = _PyEval_GetBuiltinId(&PyId_getattr); if (st->getattr == NULL) @@ -1160,7 +1191,6 @@ _Pickler_SetProtocol(PicklerObject *self, PyObject *protocol, int fix_imports) static int _Pickler_SetOutputStream(PicklerObject *self, PyObject *file) { - _Py_IDENTIFIER(write); assert(file != NULL); if (_PyObject_LookupAttrId(file, &PyId_write, &self->write) < 0) { return -1; @@ -1511,10 +1541,6 @@ _Unpickler_New(void) static int _Unpickler_SetInputStream(UnpicklerObject *self, PyObject *file) { - _Py_IDENTIFIER(peek); - _Py_IDENTIFIER(read); - _Py_IDENTIFIER(readline); - if (_PyObject_LookupAttrId(file, &PyId_peek, &self->peek) < 0) { return -1; } @@ -1766,9 +1792,6 @@ whichmodule(PyObject *global, PyObject *dotted_path) PyObject *module = NULL; Py_ssize_t i; PyObject *modules; - _Py_IDENTIFIER(__module__); - _Py_IDENTIFIER(modules); - _Py_IDENTIFIER(__main__); if (_PyObject_LookupAttrId(global, &PyId___module__, &module_name) < 0) { return NULL; @@ -2236,7 +2259,6 @@ save_bytes(PicklerObject *self, PyObject *obj) PyUnicode_DecodeLatin1(PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj), "strict"); - _Py_IDENTIFIER(latin1); if (unicode_str == NULL) return -1; @@ -3058,7 +3080,6 @@ save_dict(PicklerObject *self, PyObject *obj) status = batch_dict_exact(self, obj); Py_LeaveRecursiveCall(); } else { - _Py_IDENTIFIER(items); items = _PyObject_CallMethodId(obj, &PyId_items, NULL); if (items == NULL) @@ -3312,8 +3333,6 @@ save_global(PicklerObject *self, PyObject *obj, PyObject *name) PyObject *cls; PickleState *st = _Pickle_GetGlobalState(); int status = 0; - _Py_IDENTIFIER(__name__); - _Py_IDENTIFIER(__qualname__); const char global_op = GLOBAL; @@ -3646,7 +3665,6 @@ static PyObject * get_class(PyObject *obj) { PyObject *cls; - _Py_IDENTIFIER(__class__); if (_PyObject_LookupAttrId(obj, &PyId___class__, &cls) == 0) { cls = (PyObject *) Py_TYPE(obj); @@ -3731,17 +3749,14 @@ save_reduce(PicklerObject *self, PyObject *args, PyObject *obj) if (self->proto >= 2) { PyObject *name; - _Py_IDENTIFIER(__name__); if (_PyObject_LookupAttrId(callable, &PyId___name__, &name) < 0) { return -1; } if (name != NULL && PyUnicode_Check(name)) { - _Py_IDENTIFIER(__newobj_ex__); use_newobj_ex = _PyUnicode_EqualToASCIIId( name, &PyId___newobj_ex__); if (!use_newobj_ex) { - _Py_IDENTIFIER(__newobj__); use_newobj = _PyUnicode_EqualToASCIIId(name, &PyId___newobj__); } } @@ -3794,7 +3809,6 @@ save_reduce(PicklerObject *self, PyObject *args, PyObject *obj) PyObject *newargs; PyObject *cls_new; Py_ssize_t i; - _Py_IDENTIFIER(__new__); newargs = PyTuple_New(PyTuple_GET_SIZE(args) + 2); if (newargs == NULL) @@ -4128,8 +4142,6 @@ save(PicklerObject *self, PyObject *obj, int pers_save) goto done; } else { - _Py_IDENTIFIER(__reduce__); - _Py_IDENTIFIER(__reduce_ex__); /* XXX: If the __reduce__ method is defined, __reduce_ex__ is @@ -4204,7 +4216,6 @@ dump(PicklerObject *self, PyObject *obj) { const char stop_op = STOP; PyObject *tmp; - _Py_IDENTIFIER(reducer_override); if (_PyObject_LookupAttrId((PyObject *)self, &PyId_reducer_override, &tmp) < 0) { @@ -4411,9 +4422,6 @@ _pickle_Pickler___init___impl(PicklerObject *self, PyObject *file, PyObject *protocol, int fix_imports) /*[clinic end generated code: output=b5f31078dab17fb0 input=4faabdbc763c2389]*/ { - _Py_IDENTIFIER(persistent_id); - _Py_IDENTIFIER(dispatch_table); - /* In case of multiple __init__() calls, clear previous content. */ if (self->write != NULL) (void)Pickler_clear(self); @@ -4804,8 +4812,6 @@ static PyTypeObject Pickler_Type = { static PyObject * find_class(UnpicklerObject *self, PyObject *module_name, PyObject *global_name) { - _Py_IDENTIFIER(find_class); - return _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_find_class, module_name, global_name, NULL); } @@ -5411,8 +5417,6 @@ instantiate(PyObject *cls, PyObject *args) into a newly created tuple. */ assert(PyTuple_Check(args)); if (!PyTuple_GET_SIZE(args) && PyType_Check(cls)) { - _Py_IDENTIFIER(__getinitargs__); - _Py_IDENTIFIER(__new__); PyObject *func; if (_PyObject_LookupAttrId(cls, &PyId___getinitargs__, &func) < 0) { return NULL; @@ -6089,7 +6093,6 @@ do_append(UnpicklerObject *self, Py_ssize_t x) } else { PyObject *extend_func; - _Py_IDENTIFIER(extend); extend_func = _PyObject_GetAttrId(list, &PyId_extend); if (extend_func != NULL) { @@ -6106,7 +6109,6 @@ do_append(UnpicklerObject *self, Py_ssize_t x) } else { PyObject *append_func; - _Py_IDENTIFIER(append); /* Even if the PEP 307 requires extend() and append() methods, fall back on append() if the object has no extend() method @@ -6235,7 +6237,6 @@ load_additems(UnpicklerObject *self) } else { PyObject *add_func; - _Py_IDENTIFIER(add); add_func = _PyObject_GetAttrId(set, &PyId_add); if (add_func == NULL) @@ -6265,7 +6266,6 @@ load_build(UnpicklerObject *self) PyObject *state, *inst, *slotstate; PyObject *setstate; int status = 0; - _Py_IDENTIFIER(__setstate__); /* Stack is ... instance, state. We want to leave instance at * the stack top, possibly mutated via instance.__setstate__(state). @@ -6315,7 +6315,6 @@ load_build(UnpicklerObject *self) PyObject *dict; PyObject *d_key, *d_value; Py_ssize_t i; - _Py_IDENTIFIER(__dict__); if (!PyDict_Check(state)) { PickleState *st = _Pickle_GetGlobalState(); @@ -6859,8 +6858,6 @@ _pickle_Unpickler___init___impl(UnpicklerObject *self, PyObject *file, const char *errors) /*[clinic end generated code: output=e2c8ce748edc57b0 input=f9b7da04f5f4f335]*/ { - _Py_IDENTIFIER(persistent_load); - /* In case of multiple __init__() calls, clear previous content. */ if (self->read != NULL) (void)Unpickler_clear(self); diff --git a/Modules/_posixsubprocess.c b/Modules/_posixsubprocess.c index 81a23c6d330037..dfe7dc34a32b65 100644 --- a/Modules/_posixsubprocess.c +++ b/Modules/_posixsubprocess.c @@ -50,12 +50,15 @@ #define POSIX_CALL(call) do { if ((call) == -1) goto error; } while (0) +_Py_IDENTIFIER(enable); +_Py_IDENTIFIER(isenabled); +_Py_IDENTIFIER(disable); + /* If gc was disabled, call gc.enable(). Return 0 on success. */ static int _enable_gc(int need_to_reenable_gc, PyObject *gc_module) { PyObject *result; - _Py_IDENTIFIER(enable); PyObject *exctype, *val, *tb; if (need_to_reenable_gc) { @@ -600,8 +603,6 @@ subprocess_fork_exec(PyObject* self, PyObject *args) /* We need to call gc.disable() when we'll be calling preexec_fn */ if (preexec_fn != Py_None) { PyObject *result; - _Py_IDENTIFIER(isenabled); - _Py_IDENTIFIER(disable); gc_module = PyImport_ImportModule("gc"); if (gc_module == NULL) diff --git a/Modules/_randommodule.c b/Modules/_randommodule.c index 6a48689204c5a5..2f1a9b58752058 100644 --- a/Modules/_randommodule.c +++ b/Modules/_randommodule.c @@ -98,7 +98,9 @@ static uint32_t genrand_int32(RandomObject *self) { uint32_t y; - static const uint32_t mag01[2] = {0x0U, MATRIX_A}; + static const uint32_t mag01[2] = { // Static is okay here (immutable data). + 0x0U, MATRIX_A + }; /* mag01[x] = x * MATRIX_A for x=0,1 */ uint32_t *mt; diff --git a/Modules/_sqlite/connection.c b/Modules/_sqlite/connection.c index e3340bf19f7bd3..00a70e16eb4c80 100644 --- a/Modules/_sqlite/connection.c +++ b/Modules/_sqlite/connection.c @@ -46,6 +46,9 @@ #endif _Py_IDENTIFIER(cursor); +_Py_IDENTIFIER(finalize); +_Py_IDENTIFIER(upper); +_Py_IDENTIFIER(_iterdump); static const char * const begin_statements[] = { "BEGIN ", @@ -692,7 +695,6 @@ void _pysqlite_final_callback(sqlite3_context* context) { PyObject* function_result; PyObject** aggregate_instance; - _Py_IDENTIFIER(finalize); int ok; PyObject *exception, *value, *tb; int restore; @@ -1176,7 +1178,6 @@ pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* iso } else { const char * const *candidate; PyObject *uppercase_level; - _Py_IDENTIFIER(upper); if (!PyUnicode_Check(isolation_level)) { PyErr_Format(PyExc_TypeError, @@ -1436,7 +1437,6 @@ pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args) static PyObject * pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args) { - _Py_IDENTIFIER(_iterdump); PyObject* retval = NULL; PyObject* module = NULL; PyObject* module_dict; @@ -1493,9 +1493,9 @@ pysqlite_connection_backup(pysqlite_Connection *self, PyObject *args, PyObject * int sleep_ms = 250; sqlite3 *bck_conn; sqlite3_backup *bck_handle; - static char *keywords[] = {"target", "pages", "progress", "name", "sleep", NULL}; + static char *kwlist[] = {"target", "pages", "progress", "name", "sleep", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|$iOsO:backup", keywords, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|$iOsO:backup", kwlist, &pysqlite_ConnectionType, &target, &pages, &progress, &name, &sleep_obj)) { return NULL; @@ -1640,7 +1640,6 @@ pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args) PyObject* name; PyObject* retval; Py_ssize_t i, len; - _Py_IDENTIFIER(upper); const char *uppercase_name_str; int rc; unsigned int kind; diff --git a/Modules/_sqlite/cursor.c b/Modules/_sqlite/cursor.c index 2bc19311a81d21..6f69d78113f23a 100644 --- a/Modules/_sqlite/cursor.c +++ b/Modules/_sqlite/cursor.c @@ -25,6 +25,9 @@ #include "module.h" #include "util.h" + +_Py_IDENTIFIER(upper); + PyObject* pysqlite_cursor_iternext(pysqlite_Cursor* self); static const char errmsg_fetch_across_rollback[] = "Cursor needed to be reset because of commit/rollback and can no longer be fetched from."; @@ -100,7 +103,6 @@ _pysqlite_get_converter(const char *keystr, Py_ssize_t keylen) PyObject *key; PyObject *upcase_key; PyObject *retval; - _Py_IDENTIFIER(upper); key = PyUnicode_FromStringAndSize(keystr, keylen); if (!key) { diff --git a/Modules/_sqlite/microprotocols.c b/Modules/_sqlite/microprotocols.c index c23b09f56b5bd1..d3ed6f3dfbad5f 100644 --- a/Modules/_sqlite/microprotocols.c +++ b/Modules/_sqlite/microprotocols.c @@ -31,6 +31,9 @@ #include "prepare_protocol.h" +_Py_IDENTIFIER(__adapt__); +_Py_IDENTIFIER(__conform__); + /** the adapters registry **/ static PyObject *psyco_adapters = NULL; @@ -75,8 +78,6 @@ pysqlite_microprotocols_add(PyTypeObject *type, PyObject *proto, PyObject *cast) PyObject * pysqlite_microprotocols_adapt(PyObject *obj, PyObject *proto, PyObject *alt) { - _Py_IDENTIFIER(__adapt__); - _Py_IDENTIFIER(__conform__); PyObject *adapter, *key, *adapted; /* we don't check for exact type conformance as specified in PEP 246 diff --git a/Modules/_sqlite/module.c b/Modules/_sqlite/module.c index c487ba98908b34..446fe5fdce3e28 100644 --- a/Modules/_sqlite/module.c +++ b/Modules/_sqlite/module.c @@ -35,6 +35,8 @@ /* static objects at module-level */ +_Py_IDENTIFIER(upper); + PyObject *pysqlite_Error = NULL; PyObject *pysqlite_Warning = NULL; PyObject *pysqlite_InterfaceError = NULL; @@ -192,7 +194,6 @@ static PyObject* module_register_converter(PyObject* self, PyObject* args) PyObject* name = NULL; PyObject* callable; PyObject* retval = NULL; - _Py_IDENTIFIER(upper); if (!PyArg_ParseTuple(args, "UO", &orig_name, &callable)) { return NULL; diff --git a/Modules/_sre.c b/Modules/_sre.c index 014cc546e345d9..b47e54b6e04383 100644 --- a/Modules/_sre.c +++ b/Modules/_sre.c @@ -1224,7 +1224,7 @@ _sre_SRE_Pattern___deepcopy__(PatternObject *self, PyObject *memo) static PyObject * pattern_repr(PatternObject *obj) { - static const struct { + static const struct { // Static is okay here (immutable data). const char *name; int value; } flag_names[] = { diff --git a/Modules/_ssl.c b/Modules/_ssl.c index 390a1af1e59de7..904e1337416c14 100644 --- a/Modules/_ssl.c +++ b/Modules/_ssl.c @@ -75,6 +75,12 @@ static PySocketModule_APIObject PySocketModule; # endif #endif + +_Py_IDENTIFIER(reason); +_Py_IDENTIFIER(library); +_Py_IDENTIFIER(verify_message); +_Py_IDENTIFIER(verify_code); + /* SSL error object */ static PyObject *PySSLErrorObject; static PyObject *PySSLCertVerificationErrorObject; @@ -577,10 +583,6 @@ fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno, PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL; PyObject *verify_obj = NULL, *verify_code_obj = NULL; PyObject *init_value, *msg, *key; - _Py_IDENTIFIER(reason); - _Py_IDENTIFIER(library); - _Py_IDENTIFIER(verify_message); - _Py_IDENTIFIER(verify_code); if (errcode != 0) { int lib, reason; @@ -5317,29 +5319,29 @@ _ssl_nid2obj_impl(PyObject *module, int nid) #ifdef _MSC_VER +static PyObject *cached_str_x509_asn = NULL; +static PyObject *cached_str_pkcs_7_asn = NULL; + static PyObject* certEncodingType(DWORD encodingType) { - static PyObject *x509_asn = NULL; - static PyObject *pkcs_7_asn = NULL; - - if (x509_asn == NULL) { - x509_asn = PyUnicode_InternFromString("x509_asn"); - if (x509_asn == NULL) + if (cached_str_x509_asn == NULL) { + cached_str_x509_asn = PyUnicode_InternFromString("x509_asn"); + if (cached_str_x509_asn == NULL) return NULL; } - if (pkcs_7_asn == NULL) { - pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn"); - if (pkcs_7_asn == NULL) + if (cached_str_pkcs_7_asn == NULL) { + cached_str_pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn"); + if (cached_str_pkcs_7_asn == NULL) return NULL; } switch(encodingType) { case X509_ASN_ENCODING: - Py_INCREF(x509_asn); - return x509_asn; + Py_INCREF(cached_str_x509_asn); + return cached_str_x509_asn; case PKCS_7_ASN_ENCODING: - Py_INCREF(pkcs_7_asn); - return pkcs_7_asn; + Py_INCREF(cached_str_pkcs_7_asn); + return cached_str_pkcs_7_asn; default: return PyLong_FromLong(encodingType); } @@ -5410,7 +5412,7 @@ ssl_collect_certificates(const char *store_name) */ HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL; - static DWORD system_stores[] = { + static const DWORD system_stores[] = { // Static is okay here (immutable data). CERT_SYSTEM_STORE_LOCAL_MACHINE, CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE, CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY, diff --git a/Modules/_testbuffer.c b/Modules/_testbuffer.c index 9d7b3e8b0b3ff0..058da706d3565a 100644 --- a/Modules/_testbuffer.c +++ b/Modules/_testbuffer.c @@ -2234,11 +2234,11 @@ ndarray_memoryview_from_buffer(PyObject *self, PyObject *dummy) const NDArrayObject *nd = (NDArrayObject *)self; const Py_buffer *view = &nd->head->base; const ndbuf_t *ndbuf; - static char format[ND_MAX_NDIM+1]; - static Py_ssize_t shape[ND_MAX_NDIM]; - static Py_ssize_t strides[ND_MAX_NDIM]; - static Py_ssize_t suboffsets[ND_MAX_NDIM]; - static Py_buffer info; + static char format[ND_MAX_NDIM+1]; // Static is okay here (testing). + static Py_ssize_t shape[ND_MAX_NDIM]; // Static is okay here (testing). + static Py_ssize_t strides[ND_MAX_NDIM]; // Static is okay here (testing). + static Py_ssize_t suboffsets[ND_MAX_NDIM]; // Static is okay here (testing). + static Py_buffer info; // Static is okay here (testing). char *p; if (!ND_IS_CONSUMER(nd)) diff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c index 04d75ace6ecf23..d1dbc6f091524e 100644 --- a/Modules/_testcapimodule.c +++ b/Modules/_testcapimodule.c @@ -32,6 +32,9 @@ # error "_testcapi must test the public Python C API, not CPython internal C API" #endif + +_Py_IDENTIFIER(__tp_del__); + static PyObject *TestError; /* set to exception object in init */ /* Raise TestError with test_name + ": " + msg, and return NULL. */ @@ -1025,11 +1028,11 @@ getargs_tuple(PyObject *self, PyObject *args) static PyObject * getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs) { - static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; - static const char fmt[] = "(ii)i|(i(ii))(iii)i"; + static char *kwlist[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; + static const char fmt[] = "(ii)i|(i(ii))(iii)i"; // Static is okay here (immutable data). int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, kwlist, &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) return NULL; @@ -1042,12 +1045,12 @@ getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject * getargs_keyword_only(PyObject *self, PyObject *args, PyObject *kwargs) { - static char *keywords[] = {"required", "optional", "keyword_only", NULL}; + static char *kwlist[] = {"required", "optional", "keyword_only", NULL}; int required = -1; int optional = -1; int keyword_only = -1; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i$i", keywords, + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i$i", kwlist, &required, &optional, &keyword_only)) return NULL; return Py_BuildValue("iii", required, optional, keyword_only); @@ -1057,12 +1060,12 @@ getargs_keyword_only(PyObject *self, PyObject *args, PyObject *kwargs) static PyObject * getargs_positional_only_and_keywords(PyObject *self, PyObject *args, PyObject *kwargs) { - static char *keywords[] = {"", "", "keyword", NULL}; + static char *kwlist[] = {"", "", "keyword", NULL}; int required = -1; int optional = -1; int keyword = -1; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii", keywords, + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii", kwlist, &required, &optional, &keyword)) return NULL; return Py_BuildValue("iii", required, optional, keyword); @@ -2732,7 +2735,7 @@ test_capsule(PyObject *self, PyObject *Py_UNUSED(ignored)) /* yeah, ordinarily I wouldn't do this either, but it's fine for this test harness. */ - static char buffer[256]; + static char buffer[256]; // Static is okay here (buffer, non-threaded). #undef FAIL #define FAIL(x) \ { \ @@ -3250,7 +3253,6 @@ test_pytime_object_to_timespec(PyObject *self, PyObject *args) static void slot_tp_del(PyObject *self) { - _Py_IDENTIFIER(__tp_del__); PyObject *del, *res; PyObject *error_type, *error_value, *error_traceback; @@ -5104,13 +5106,13 @@ static struct PyMemberDef test_members[] = { static PyObject * test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { - static char *keywords[] = { + static char *kwlist[] = { "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET", "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE", "T_LONGLONG", "T_ULONGLONG", NULL}; - static const char fmt[] = "|bbBhHiIlknfds#LK"; + static const char fmt[] = "|bbBhHiIlknfds#LK"; // Static is okay here (immutable data). test_structmembers *ob; const char *s = NULL; Py_ssize_t string_len = 0; @@ -5118,7 +5120,7 @@ test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) if (ob == NULL) return NULL; memset(&ob->structmembers, 0, sizeof(all_structmembers)); - if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, kwlist, &ob->structmembers.bool_member, &ob->structmembers.byte_member, &ob->structmembers.ubyte_member, diff --git a/Modules/_threadmodule.c b/Modules/_threadmodule.c index a123cd0efd6279..6ecdc1b6154e3c 100644 --- a/Modules/_threadmodule.c +++ b/Modules/_threadmodule.c @@ -699,7 +699,7 @@ local_new(PyTypeObject *type, PyObject *args, PyObject *kw) { localobject *self; PyObject *wr; - static PyMethodDef wr_callback_def = { + static PyMethodDef wr_callback_def = { // Static is okay here (dynamic method def). "_localdummy_destroyed", (PyCFunction) _localdummy_destroyed, METH_O }; diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c index 613a95b0897255..57f69308450e6b 100644 --- a/Modules/_tkinter.c +++ b/Modules/_tkinter.c @@ -100,13 +100,23 @@ Copyright (C) 1994 Steen Lumholt. #include #define WAIT_FOR_STDIN +static int tcl_library_path_initialized = 0; +static PyObject *cached_tcl_library_path = NULL; + static PyObject * _get_tcl_lib_path() { - static PyObject *tcl_library_path = NULL; - static int already_checked = 0; - - if (already_checked == 0) { + PyObject *tcl_library_path = cached_tcl_library_path; + /* Note that we do not check if tcl_library_path is NULL, where NULL + * indicates that either it hasn't been cached yet or the first + * attempt failed. This is on purpose. The first time will cause + * the caller to fail, but subsequent calls will return NULL with + * no exception set. The callers silently ignore that case. + * XXX Is that really on purpose? Shouldn't the callers either + * always fail or always silently ignore the failure (and maybe + * emit a warning)? + */ + if (tcl_library_path_initialized == 0) { PyObject *prefix; struct stat stat_buf; int stat_return_value; @@ -153,7 +163,8 @@ _get_tcl_lib_path() tcl_library_path = NULL; #endif } - already_checked = 1; + tcl_library_path_initialized = 1; + cached_tcl_library_path = tcl_library_path; } return tcl_library_path; } diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c index 4be3beb29ccbae..5f36fac8ffad5e 100644 --- a/Modules/arraymodule.c +++ b/Modules/arraymodule.c @@ -15,6 +15,12 @@ #endif /* HAVE_SYS_TYPES_H */ #endif /* !STDC_HEADERS */ +_Py_IDENTIFIER(iter); +_Py_IDENTIFIER(read); +_Py_IDENTIFIER(write); +_Py_IDENTIFIER(_array_reconstructor); +_Py_IDENTIFIER(__dict__); + /*[clinic input] module array [clinic start generated code]*/ @@ -1432,7 +1438,6 @@ array_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n) PyObject *b, *res; Py_ssize_t itemsize = self->ob_descr->itemsize; Py_ssize_t nbytes; - _Py_IDENTIFIER(read); int not_enough_bytes; if (n < 0) { @@ -1500,7 +1505,6 @@ array_array_tofile(arrayobject *self, PyObject *f) char* ptr = self->ob_item + i*BLOCKSIZE; Py_ssize_t size = BLOCKSIZE; PyObject *bytes, *res; - _Py_IDENTIFIER(write); if (i*BLOCKSIZE + size > nbytes) size = nbytes - i*BLOCKSIZE; @@ -2164,6 +2168,8 @@ array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype, return result; } +static PyObject *cached_array_reconstructor = NULL; + /*[clinic input] array.array.__reduce_ex__ @@ -2182,20 +2188,17 @@ array_array___reduce_ex__(arrayobject *self, PyObject *value) PyObject *array_str; int typecode = self->ob_descr->typecode; int mformat_code; - static PyObject *array_reconstructor = NULL; long protocol; - _Py_IDENTIFIER(_array_reconstructor); - _Py_IDENTIFIER(__dict__); - if (array_reconstructor == NULL) { + if (cached_array_reconstructor == NULL) { PyObject *array_module = PyImport_ImportModule("array"); if (array_module == NULL) return NULL; - array_reconstructor = _PyObject_GetAttrId( + cached_array_reconstructor = _PyObject_GetAttrId( array_module, &PyId__array_reconstructor); Py_DECREF(array_module); - if (array_reconstructor == NULL) + if (cached_array_reconstructor == NULL) return NULL; } @@ -2248,7 +2251,7 @@ array_array___reduce_ex__(arrayobject *self, PyObject *value) return NULL; } result = Py_BuildValue( - "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode, + "O(OCiN)O", cached_array_reconstructor, Py_TYPE(self), typecode, mformat_code, array_str, dict); Py_DECREF(dict); return result; @@ -2943,7 +2946,6 @@ static PyObject * array_arrayiterator___reduce___impl(arrayiterobject *self) /*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/ { - _Py_IDENTIFIER(iter); PyObject *func = _PyEval_GetBuiltinId(&PyId_iter); if (self->ao == NULL) { return Py_BuildValue("N(())", func); diff --git a/Modules/cjkcodecs/_codecs_hk.c b/Modules/cjkcodecs/_codecs_hk.c index 4f21569a0ce73f..a9ddfa1d42d759 100644 --- a/Modules/cjkcodecs/_codecs_hk.c +++ b/Modules/cjkcodecs/_codecs_hk.c @@ -16,13 +16,13 @@ static const encode_map *big5_encmap = NULL; static const decode_map *big5_decmap = NULL; +static int big5hkscs_initialized = 0; + CODEC_INIT(big5hkscs) { - static int initialized = 0; - - if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap)) + if (!big5hkscs_initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap)) return -1; - initialized = 1; + big5hkscs_initialized = 1; return 0; } diff --git a/Modules/cjkcodecs/_codecs_iso2022.c b/Modules/cjkcodecs/_codecs_iso2022.c index 7394cf67e0e7dd..70c111e1ff3312 100644 --- a/Modules/cjkcodecs/_codecs_iso2022.c +++ b/Modules/cjkcodecs/_codecs_iso2022.c @@ -566,16 +566,16 @@ DECMAP(gb2312) /*-*- mapping access functions -*-*/ +static int ksx1001_initialized = 0; + static int ksx1001_init(void) { - static int initialized = 0; - - if (!initialized && ( + if (!ksx1001_initialized && ( IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) || IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap))) return -1; - initialized = 1; + ksx1001_initialized = 1; return 0; } @@ -603,16 +603,16 @@ ksx1001_encoder(const Py_UCS4 *data, Py_ssize_t *length) return MAP_UNMAPPABLE; } +static int jisx0208_initialized = 0; + static int jisx0208_init(void) { - static int initialized = 0; - - if (!initialized && ( + if (!jisx0208_initialized && ( IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap))) return -1; - initialized = 1; + jisx0208_initialized = 1; return 0; } @@ -644,16 +644,16 @@ jisx0208_encoder(const Py_UCS4 *data, Py_ssize_t *length) return MAP_UNMAPPABLE; } +static int jisx0212_initialized = 0; + static int jisx0212_init(void) { - static int initialized = 0; - - if (!initialized && ( + if (!jisx0212_initialized && ( IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap))) return -1; - initialized = 1; + jisx0212_initialized = 1; return 0; } @@ -681,12 +681,12 @@ jisx0212_encoder(const Py_UCS4 *data, Py_ssize_t *length) return MAP_UNMAPPABLE; } +static int jisx0213_initialized = 0; + static int jisx0213_init(void) { - static int initialized = 0; - - if (!initialized && ( + if (!jisx0213_initialized && ( jisx0208_init() || IMPORT_MAP(jp, jisx0213_bmp, &jisx0213_bmp_encmap, NULL) || @@ -703,7 +703,7 @@ jisx0213_init(void) IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap, &jisx0213_pair_decmap))) return -1; - initialized = 1; + jisx0213_initialized = 1; return 0; } @@ -960,16 +960,16 @@ jisx0201_k_encoder(const Py_UCS4 *data, Py_ssize_t *length) return coded - 0x80; } +static int gb2312_initialized = 0; + static int gb2312_init(void) { - static int initialized = 0; - - if (!initialized && ( + if (!gb2312_initialized && ( IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) || IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap))) return -1; - initialized = 1; + gb2312_initialized = 1; return 0; } diff --git a/Modules/cjkcodecs/cjkcodecs.h b/Modules/cjkcodecs/cjkcodecs.h index b67f3482faf8da..e5e1ea035bf8ca 100644 --- a/Modules/cjkcodecs/cjkcodecs.h +++ b/Modules/cjkcodecs/cjkcodecs.h @@ -63,6 +63,7 @@ struct pair_encodemap { static const MultibyteCodec *codec_list; static const struct dbcs_map *mapping_list; +// Macros for building encoding-specific function headers: #define CODEC_INIT(encoding) \ static int encoding##_codec_init(const void *config) @@ -202,6 +203,7 @@ static const struct dbcs_map *mapping_list; #define TRYMAP_DEC(charset, assi, c1, c2) \ _TRYMAP_DEC(&charset##_decmap[c1], assi, c2) +// The two static locals in these macros are okay (immutable data). #define BEGIN_MAPPINGS_LIST static const struct dbcs_map _mapping_list[] = { #define MAPPING_ENCONLY(enc) {#enc, (void*)enc##_encmap, NULL}, #define MAPPING_DECONLY(enc) {#enc, NULL, (void*)enc##_decmap}, @@ -211,6 +213,7 @@ static const struct dbcs_map *mapping_list; static const struct dbcs_map *mapping_list = \ (const struct dbcs_map *)_mapping_list; +// The two static locals in these macros are okay (immutable data). #define BEGIN_CODECS_LIST static const MultibyteCodec _codec_list[] = { #define _STATEFUL_METHODS(enc) \ enc##_encode, \ @@ -242,11 +245,11 @@ static const struct dbcs_map *mapping_list; + static PyObject *cofunc = NULL; + static PyObject * getmultibytecodec(void) { - static PyObject *cofunc = NULL; - if (cofunc == NULL) { PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec"); if (mod == NULL) diff --git a/Modules/expat/xmlparse.c b/Modules/expat/xmlparse.c index c4f3ffc215c9ef..14aa1d01b0b6c5 100644 --- a/Modules/expat/xmlparse.c +++ b/Modules/expat/xmlparse.c @@ -2457,7 +2457,7 @@ XML_ExpatVersionInfo(void) const XML_Feature * XMLCALL XML_GetFeatureList(void) { - static const XML_Feature features[] = { + static const XML_Feature features[] = { // Static is okay here (immutable data). {XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"), sizeof(XML_Char)}, {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"), @@ -3561,7 +3561,7 @@ static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, const XML_Char *uri, BINDING **bindingsPtr) { - static const XML_Char xmlNamespace[] = { + static const XML_Char xmlNamespace[] = { // Static is okay here (immutable data). ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, @@ -3569,17 +3569,19 @@ addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, ASCII_n, ASCII_a, ASCII_m, ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0' }; - static const int xmlLen = - (int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1; - static const XML_Char xmlnsNamespace[] = { + //static const int xmlLen = (int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1; // Static is okay here (immutable data). + static const int xmlLen = // Static is okay here (immutable data). + (int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1; + static const XML_Char xmlnsNamespace[] = { // Static is okay here (immutable data). ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x, ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0' }; - static const int xmlnsLen = - (int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1; + //static const int xmlnsLen = (int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1; // Static is okay here (immutable data). + static const int xmlnsLen = // Static is okay here (immutable data). + (int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1; XML_Bool mustBeXML = XML_FALSE; XML_Bool isXML = XML_TRUE; @@ -4305,27 +4307,44 @@ doProlog(XML_Parser parser, XML_Bool haveMore) { #ifdef XML_DTD - static const XML_Char externalSubsetName[] = { ASCII_HASH , '\0' }; + static const XML_Char externalSubsetName[] = { // Static is okay here (immutable data). + ASCII_HASH , + '\0' + }; #endif /* XML_DTD */ - static const XML_Char atypeCDATA[] = - { ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' }; - static const XML_Char atypeID[] = { ASCII_I, ASCII_D, '\0' }; - static const XML_Char atypeIDREF[] = - { ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0' }; - static const XML_Char atypeIDREFS[] = - { ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0' }; - static const XML_Char atypeENTITY[] = - { ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0' }; - static const XML_Char atypeENTITIES[] = { ASCII_E, ASCII_N, - ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, '\0' }; - static const XML_Char atypeNMTOKEN[] = { - ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0' }; - static const XML_Char atypeNMTOKENS[] = { ASCII_N, ASCII_M, ASCII_T, - ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, '\0' }; - static const XML_Char notationPrefix[] = { ASCII_N, ASCII_O, ASCII_T, - ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0' }; - static const XML_Char enumValueSep[] = { ASCII_PIPE, '\0' }; - static const XML_Char enumValueStart[] = { ASCII_LPAREN, '\0' }; + static const XML_Char atypeCDATA[] = { // Static is okay here (immutable data). + ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, + '\0' }; + static const XML_Char atypeID[] = { // Static is okay here (immutable data). + ASCII_I, ASCII_D, + '\0' }; + static const XML_Char atypeIDREF[] = { // Static is okay here (immutable data). + ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, + '\0' }; + static const XML_Char atypeIDREFS[] = { // Static is okay here (immutable data). + ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, + '\0' }; + static const XML_Char atypeENTITY[] = { // Static is okay here (immutable data). + ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, + '\0' }; + static const XML_Char atypeENTITIES[] = { // Static is okay here (immutable data). + ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, + '\0' }; + static const XML_Char atypeNMTOKEN[] = { // Static is okay here (immutable data). + ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, + '\0' }; + static const XML_Char atypeNMTOKENS[] = { // Static is okay here (immutable data). + ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, + '\0' }; + static const XML_Char notationPrefix[] = { // Static is okay here (immutable data). + ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, + '\0' }; + static const XML_Char enumValueSep[] = { // Static is okay here (immutable data). + ASCII_PIPE, '\0' + }; + static const XML_Char enumValueStart[] = { // Static is okay here (immutable data). + ASCII_LPAREN, '\0' + }; /* save one level of indirection */ DTD * const dtd = parser->m_dtd; diff --git a/Modules/expat/xmlrole.c b/Modules/expat/xmlrole.c index 708507d575be84..fbff88a7693295 100644 --- a/Modules/expat/xmlrole.c +++ b/Modules/expat/xmlrole.c @@ -830,7 +830,7 @@ attlist2(PROLOG_STATE *state, return XML_ROLE_ATTLIST_NONE; case XML_TOK_NAME: { - static const char * const types[] = { + static const char * const types[] = { // Static is okay here (immutable data). KW_CDATA, KW_ID, KW_IDREF, diff --git a/Modules/expat/xmltok.c b/Modules/expat/xmltok.c index 6371a350dadf96..e6840953acc445 100644 --- a/Modules/expat/xmltok.c +++ b/Modules/expat/xmltok.c @@ -1619,7 +1619,7 @@ static const char KW_UTF_16LE[] = { static int FASTCALL getEncodingIndex(const char *name) { - static const char * const encodingNames[] = { + static const char * const encodingNames[] = { // Static is okay here (immutable data). KW_ISO_8859_1, KW_US_ASCII, KW_UTF_8, diff --git a/Modules/expat/xmltok_impl.c b/Modules/expat/xmltok_impl.c index 4d9ae7dc3896b8..5a9acda99265a7 100644 --- a/Modules/expat/xmltok_impl.c +++ b/Modules/expat/xmltok_impl.c @@ -327,8 +327,9 @@ static int PTRCALL PREFIX(scanCdataSection)(const ENCODING *UNUSED_P(enc), const char *ptr, const char *end, const char **nextTokPtr) { - static const char CDATA_LSQB[] = { ASCII_C, ASCII_D, ASCII_A, - ASCII_T, ASCII_A, ASCII_LSQB }; + static const char CDATA_LSQB[] = { // Static is okay here (immutable data). + ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, ASCII_LSQB + }; int i; /* CDATA[ */ REQUIRE_CHARS(enc, ptr, end, 6); diff --git a/Modules/faulthandler.c b/Modules/faulthandler.c index 63a9b91ac469ee..e0d7c808e72197 100644 --- a/Modules/faulthandler.c +++ b/Modules/faulthandler.c @@ -218,7 +218,7 @@ static void faulthandler_dump_traceback(int fd, int all_threads, PyInterpreterState *interp) { - static volatile int reentrant = 0; + static volatile int reentrant = 0; // Static is okay here (process-global). PyThreadState *tstate; if (reentrant) diff --git a/Modules/getaddrinfo.c b/Modules/getaddrinfo.c index 5aaa6e7c8144f7..dd527e140ccf13 100644 --- a/Modules/getaddrinfo.c +++ b/Modules/getaddrinfo.c @@ -246,16 +246,16 @@ getaddrinfo(const char*hostname, const char*servname, u_short port; #ifdef FAITH - static int firsttime = 1; + static int getaddrinfo_firsttime = 1; // Static is okay here (process-global). - if (firsttime) { + if (getaddrinfo_firsttime) { /* translator hack */ { const char *q = getenv("GAI"); if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) translate = YES; } - firsttime = 0; + getaddrinfo_firsttime = 0; } #endif diff --git a/Modules/getbuildinfo.c b/Modules/getbuildinfo.c index 5f941a26e1d54c..02c9f0c3cb49d3 100644 --- a/Modules/getbuildinfo.c +++ b/Modules/getbuildinfo.c @@ -34,9 +34,9 @@ const char * Py_GetBuildInfo(void) { - static char buildinfo[50 + sizeof(GITVERSION) + - ((sizeof(GITTAG) > sizeof(GITBRANCH)) ? - sizeof(GITTAG) : sizeof(GITBRANCH))]; + static char buildinfo[ // Static is okay here (buffer, non-threaded). + 50 + sizeof(GITVERSION) + ((sizeof(GITTAG) > sizeof(GITBRANCH)) ? + sizeof(GITTAG) : sizeof(GITBRANCH))]; const char *revision = _Py_gitversion(); const char *sep = *revision ? ":" : ""; const char *gitid = _Py_gitidentifier(); diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c index 103029d251e0da..7631f77ad8b50c 100644 --- a/Modules/itertoolsmodule.c +++ b/Modules/itertoolsmodule.c @@ -4,6 +4,12 @@ #include "pycore_tupleobject.h" #include "structmember.h" + +_Py_IDENTIFIER(fillvalue); +_Py_IDENTIFIER(iter); +_Py_IDENTIFIER(__copy__); +_Py_IDENTIFIER(__setstate__); + /* Itertools module written and maintained by Raymond D. Hettinger */ @@ -369,7 +375,6 @@ _grouper_next(_grouperobject *igo) static PyObject * _grouper_reduce(_grouperobject *lz, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); if (((groupbyobject *)lz->parent)->currgrouper != lz) { return Py_BuildValue("N(())", _PyEval_GetBuiltinId(&PyId_iter)); } @@ -875,7 +880,6 @@ itertools_tee_impl(PyObject *module, PyObject *iterable, Py_ssize_t n) { Py_ssize_t i; PyObject *it, *copyable, *copyfunc, *result; - _Py_IDENTIFIER(__copy__); if (n < 0) { PyErr_SetString(PyExc_ValueError, "n must be >= 0"); @@ -1042,7 +1046,6 @@ cycle_reduce(cycleobject *lz, PyObject *Py_UNUSED(ignored)) if (it == NULL) return NULL; if (lz->index != 0) { - _Py_IDENTIFIER(__setstate__); PyObject *res = _PyObject_CallMethodId(it, &PyId___setstate__, "n", lz->index); if (res == NULL) { @@ -4245,9 +4248,9 @@ repeat_new(PyTypeObject *type, PyObject *args, PyObject *kwds) repeatobject *ro; PyObject *element; Py_ssize_t cnt = -1, n_kwds = 0; - static char *kwargs[] = {"object", "times", NULL}; + static char *kwlist[] = {"object", "times", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwlist, &element, &cnt)) return NULL; @@ -4400,7 +4403,6 @@ static PyTypeObject ziplongest_type; static PyObject * zip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - _Py_IDENTIFIER(fillvalue); ziplongestobject *lz; Py_ssize_t i; PyObject *ittuple; /* tuple of iterators */ diff --git a/Modules/main.c b/Modules/main.c index b47ac70d62cfb1..6759b383a690c1 100644 --- a/Modules/main.c +++ b/Modules/main.c @@ -31,6 +31,9 @@ extern "C" { #endif + +_Py_IDENTIFIER(path); + /* --- pymain_init() ---------------------------------------------- */ static _PyInitError @@ -124,7 +127,6 @@ pymain_get_importer(const wchar_t *filename) static int pymain_sys_path_add_path0(PyInterpreterState *interp, PyObject *path0) { - _Py_IDENTIFIER(path); PyObject *sys_path; PyObject *sysdict = interp->sysdict; if (sysdict != NULL) { diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c index ba8423211c2b53..f3e5592365acd3 100644 --- a/Modules/mathmodule.c +++ b/Modules/mathmodule.c @@ -55,6 +55,11 @@ raised for division by zero and mod by zero. #include "Python.h" #include "_math.h" + +_Py_IDENTIFIER(__ceil__); +_Py_IDENTIFIER(__floor__); +_Py_IDENTIFIER(__trunc__); + #include "clinic/mathmodule.c.h" /*[clinic input] @@ -1108,7 +1113,6 @@ static PyObject * math_ceil(PyObject *module, PyObject *number) /*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/ { - _Py_IDENTIFIER(__ceil__); PyObject *method, *result; method = _PyObject_LookupSpecial(number, &PyId___ceil__); @@ -1166,7 +1170,6 @@ static PyObject * math_floor(PyObject *module, PyObject *number) /*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/ { - _Py_IDENTIFIER(__floor__); PyObject *method, *result; method = _PyObject_LookupSpecial(number, &PyId___floor__); @@ -1757,7 +1760,6 @@ static PyObject * math_trunc(PyObject *module, PyObject *x) /*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/ { - _Py_IDENTIFIER(__trunc__); PyObject *trunc, *result; if (Py_TYPE(x)->tp_dict == NULL) { diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c index 6ddbf70d9a9789..b6d9eaede985ba 100644 --- a/Modules/mmapmodule.c +++ b/Modules/mmapmodule.c @@ -79,6 +79,9 @@ my_getpagesize(void) # define MAP_ANONYMOUS MAP_ANON #endif + +_Py_IDENTIFIER(close); + typedef enum { ACCESS_DEFAULT, @@ -690,8 +693,6 @@ mmap__enter__method(mmap_object *self, PyObject *args) static PyObject * mmap__exit__method(PyObject *self, PyObject *args) { - _Py_IDENTIFIER(close); - return _PyObject_CallMethodId(self, &PyId_close, NULL); } @@ -1055,11 +1056,11 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ; int devzero = -1; int access = (int)ACCESS_DEFAULT; - static char *keywords[] = {"fileno", "length", - "flags", "prot", - "access", "offset", NULL}; + static char *kwlist[] = {"fileno", "length", + "flags", "prot", + "access", "offset", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|iii" _Py_PARSE_OFF_T, keywords, + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|iii" _Py_PARSE_OFF_T, kwlist, &fd, &map_size, &flags, &prot, &access, &offset)) return NULL; @@ -1221,11 +1222,11 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) HANDLE fh = 0; int access = (access_mode)ACCESS_DEFAULT; DWORD flProtect, dwDesiredAccess; - static char *keywords[] = { "fileno", "length", - "tagname", - "access", "offset", NULL }; + static char *kwlist[] = { "fileno", "length", + "tagname", + "access", "offset", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|ziL", keywords, + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|ziL", kwlist, &fileno, &map_size, &tagname, &access, &offset)) { return NULL; diff --git a/Modules/nismodule.c b/Modules/nismodule.c index a24978e0686705..e69dc3d5fca462 100644 --- a/Modules/nismodule.c +++ b/Modules/nismodule.c @@ -337,7 +337,7 @@ static nisresp_maplist * nisproc_maplist_2(domainname *argp, CLIENT *clnt) { - static nisresp_maplist res; + static nisresp_maplist res; // Static is okay here (non-threaded?). memset(&res, 0, sizeof(res)); if (clnt_call(clnt, YPPROC_MAPLIST, diff --git a/Modules/ossaudiodev.c b/Modules/ossaudiodev.c index 2222148c85161c..bc0d73858e8c45 100644 --- a/Modules/ossaudiodev.c +++ b/Modules/ossaudiodev.c @@ -51,6 +51,9 @@ typedef unsigned long uint32_t; #endif + +_Py_IDENTIFIER(close); + typedef struct { PyObject_HEAD const char *devicename; /* name of the device file */ @@ -537,8 +540,6 @@ oss_self(PyObject *self, PyObject *unused) static PyObject * oss_exit(PyObject *self, PyObject *unused) { - _Py_IDENTIFIER(close); - PyObject *ret = _PyObject_CallMethodId(self, &PyId_close, NULL); if (!ret) return NULL; diff --git a/Modules/parsermodule.c b/Modules/parsermodule.c index 0f681622f28820..9dbab48212ec56 100644 --- a/Modules/parsermodule.c +++ b/Modules/parsermodule.c @@ -46,6 +46,11 @@ extern grammar _PyParser_Grammar; /* From graminit.c */ #define NOTE(x) #endif + +_Py_IDENTIFIER(pickle); +_Py_IDENTIFIER(sequence2st); +_Py_IDENTIFIER(_pickler); + /* String constants used to initialize module attributes. * */ @@ -382,15 +387,15 @@ parser_st2tuple(PyST_Object *self, PyObject *args, PyObject *kw) PyObject *res = 0; int ok; - static char *keywords[] = {"st", "line_info", "col_info", NULL}; + static char *kwlist[] = {"st", "line_info", "col_info", NULL}; if (self == NULL || PyModule_Check(self)) { - ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|pp:st2tuple", keywords, + ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|pp:st2tuple", kwlist, &PyST_Type, &self, &line_info, &col_info); } else - ok = PyArg_ParseTupleAndKeywords(args, kw, "|pp:totuple", &keywords[1], + ok = PyArg_ParseTupleAndKeywords(args, kw, "|pp:totuple", &kwlist[1], &line_info, &col_info); if (ok != 0) { /* @@ -418,14 +423,14 @@ parser_st2list(PyST_Object *self, PyObject *args, PyObject *kw) PyObject *res = 0; int ok; - static char *keywords[] = {"st", "line_info", "col_info", NULL}; + static char *kwlist[] = {"st", "line_info", "col_info", NULL}; if (self == NULL || PyModule_Check(self)) - ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|pp:st2list", keywords, + ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|pp:st2list", kwlist, &PyST_Type, &self, &line_info, &col_info); else - ok = PyArg_ParseTupleAndKeywords(args, kw, "|pp:tolist", &keywords[1], + ok = PyArg_ParseTupleAndKeywords(args, kw, "|pp:tolist", &kwlist[1], &line_info, &col_info); if (ok) { /* @@ -454,14 +459,14 @@ parser_compilest(PyST_Object *self, PyObject *args, PyObject *kw) PyObject* filename = NULL; int ok; - static char *keywords[] = {"st", "filename", NULL}; + static char *kwlist[] = {"st", "filename", NULL}; if (self == NULL || PyModule_Check(self)) - ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|O&:compilest", keywords, + ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|O&:compilest", kwlist, &PyST_Type, &self, PyUnicode_FSDecoder, &filename); else - ok = PyArg_ParseTupleAndKeywords(args, kw, "|O&:compile", &keywords[1], + ok = PyArg_ParseTupleAndKeywords(args, kw, "|O&:compile", &kwlist[1], PyUnicode_FSDecoder, &filename); if (!ok) goto error; @@ -504,13 +509,13 @@ parser_isexpr(PyST_Object *self, PyObject *args, PyObject *kw) PyObject* res = 0; int ok; - static char *keywords[] = {"st", NULL}; + static char *kwlist[] = {"st", NULL}; if (self == NULL || PyModule_Check(self)) - ok = PyArg_ParseTupleAndKeywords(args, kw, "O!:isexpr", keywords, + ok = PyArg_ParseTupleAndKeywords(args, kw, "O!:isexpr", kwlist, &PyST_Type, &self); else - ok = PyArg_ParseTupleAndKeywords(args, kw, ":isexpr", &keywords[1]); + ok = PyArg_ParseTupleAndKeywords(args, kw, ":isexpr", &kwlist[1]); if (ok) { /* Check to see if the ST represents an expression or not. */ @@ -527,13 +532,13 @@ parser_issuite(PyST_Object *self, PyObject *args, PyObject *kw) PyObject* res = 0; int ok; - static char *keywords[] = {"st", NULL}; + static char *kwlist[] = {"st", NULL}; if (self == NULL || PyModule_Check(self)) - ok = PyArg_ParseTupleAndKeywords(args, kw, "O!:issuite", keywords, + ok = PyArg_ParseTupleAndKeywords(args, kw, "O!:issuite", kwlist, &PyST_Type, &self); else - ok = PyArg_ParseTupleAndKeywords(args, kw, ":issuite", &keywords[1]); + ok = PyArg_ParseTupleAndKeywords(args, kw, ":issuite", &kwlist[1]); if (ok) { /* Check to see if the ST represents an expression or not. */ @@ -570,9 +575,9 @@ parser_do_parse(PyObject *args, PyObject *kw, const char *argspec, int type) int flags = 0; perrdetail err; - static char *keywords[] = {"source", NULL}; + static char *kwlist[] = {"source", NULL}; - if (PyArg_ParseTupleAndKeywords(args, kw, argspec, keywords, &string)) { + if (PyArg_ParseTupleAndKeywords(args, kw, argspec, kwlist, &string)) { node* n = PyParser_ParseStringFlagsFilenameEx(string, NULL, &_PyParser_Grammar, (type == PyST_EXPR) @@ -755,9 +760,9 @@ parser_tuple2st(PyST_Object *self, PyObject *args, PyObject *kw) PyObject *tuple; node *tree; - static char *keywords[] = {"sequence", NULL}; + static char *kwlist[] = {"sequence", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kw, "O:sequence2st", keywords, + if (!PyArg_ParseTupleAndKeywords(args, kw, "O:sequence2st", kwlist, &tuple)) return (0); if (!PySequence_Check(tuple)) { @@ -1197,9 +1202,6 @@ PyInit_parser(void) copyreg = PyImport_ImportModuleNoBlock("copyreg"); if (copyreg != NULL) { PyObject *func, *pickler; - _Py_IDENTIFIER(pickle); - _Py_IDENTIFIER(sequence2st); - _Py_IDENTIFIER(_pickler); func = _PyObject_GetAttrId(copyreg, &PyId_pickle); pickle_constructor = _PyObject_GetAttrId(module, &PyId_sequence2st); diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c index aca64efeb1e37f..790f834e54ddb3 100644 --- a/Modules/posixmodule.c +++ b/Modules/posixmodule.c @@ -379,6 +379,11 @@ extern char *ctermid_r(char *); # include #endif + +_Py_IDENTIFIER(st_mode); +_Py_IDENTIFIER(__fspath__); +_Py_IDENTIFIER(struct_rusage); + #ifdef HAVE_FORK static void run_at_forkers(PyObject *lst, int reverse) @@ -963,7 +968,6 @@ path_converter(PyObject *o, void *p) if (!is_index && !is_buffer && !is_unicode && !is_bytes) { /* Inline PyOS_FSPath() for better error messages. */ - _Py_IDENTIFIER(__fspath__); PyObject *func, *res; func = _PyObject_LookupSpecial(o, &PyId___fspath__); @@ -7360,12 +7364,12 @@ os_setgroups(PyObject *module, PyObject *groups) #endif /* HAVE_SETGROUPS */ #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4) +static PyObject *struct_rusage = NULL; + static PyObject * wait_helper(pid_t pid, int status, struct rusage *ru) { PyObject *result; - static PyObject *struct_rusage; - _Py_IDENTIFIER(struct_rusage); if (pid == -1) return posix_error(); @@ -7871,7 +7875,7 @@ os_symlink_impl(PyObject *module, path_t *src, path_t *dst, DWORD flags = 0; /* Assumed true, set to false if detected to not be available. */ - static int windows_has_symlink_unprivileged_flag = TRUE; + static int windows_has_symlink_unprivileged_flag = TRUE; // Static is okay here (process-global). #else int result; #endif @@ -8344,7 +8348,7 @@ os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable) #if defined(HAVE_DUP3) && \ !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)) /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */ - static int dup3_works = -1; + static int dup3_works = -1; // Static is okay here (process-global). #endif if (fd < 0 || fd2 < 0) { @@ -8845,19 +8849,19 @@ posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict) struct sf_hdtr sf; int flags = 0; /* Beware that "in" clashes with Python's own "in" operator keyword */ - static char *keywords[] = {"out", "in", - "offset", "count", - "headers", "trailers", "flags", NULL}; + static char *kwlist[] = {"out", "in", + "offset", "count", + "headers", "trailers", "flags", NULL}; sf.headers = NULL; sf.trailers = NULL; #ifdef __APPLE__ if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile", - keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes, + kwlist, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes, #else if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile", - keywords, &out, &in, Py_off_t_converter, &offset, &len, + kwlist, &out, &in, Py_off_t_converter, &offset, &len, #endif &headers, &trailers, &flags)) return NULL; @@ -8961,10 +8965,10 @@ posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict) #else Py_ssize_t count; PyObject *offobj; - static char *keywords[] = {"out", "in", - "offset", "count", NULL}; + static char *kwlist[] = {"out", "in", + "offset", "count", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile", - keywords, &out, &in, &offobj, &count)) + kwlist, &out, &in, &offobj, &count)) return NULL; #ifdef __linux__ if (offobj == Py_None) { @@ -11554,7 +11558,9 @@ os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute, for (i = 0; ; i++) { void *ptr; ssize_t result; - static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0}; + static const Py_ssize_t buffer_sizes[] = { // Static is okay here (immutable data). + 128, XATTR_SIZE_MAX, 0 + }; Py_ssize_t buffer_size = buffer_sizes[i]; if (!buffer_size) { path_error(path); @@ -11720,7 +11726,9 @@ os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks) for (i = 0; ; i++) { const char *start, *trace, *end; ssize_t length; - static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 }; + static const Py_ssize_t buffer_sizes[] = { // Static is okay here (immutable data). + 256, XATTR_LIST_MAX, 0 + }; Py_ssize_t buffer_size = buffer_sizes[i]; if (!buffer_size) { /* ERANGE */ @@ -11946,7 +11954,7 @@ os_cpu_count_impl(PyObject *module) /* Vista is supported and the GetMaximumProcessorCount API is Win7+ Need to fallback to Vista behavior if this call isn't present */ HINSTANCE hKernel32; - static DWORD(CALLBACK *_GetMaximumProcessorCount)(WORD) = NULL; + static DWORD(CALLBACK *_GetMaximumProcessorCount)(WORD) = NULL; // Static is okay here (buffer, non-threaded). Py_BEGIN_ALLOW_THREADS hKernel32 = GetModuleHandleW(L"KERNEL32"); *(FARPROC*)&_GetMaximumProcessorCount = GetProcAddress(hKernel32, @@ -12286,7 +12294,6 @@ DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits #ifdef MS_WINDOWS unsigned long dir_bits; #endif - _Py_IDENTIFIER(st_mode); #ifdef MS_WINDOWS is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK; @@ -13066,7 +13073,6 @@ PyOS_FSPath(PyObject *path) { /* For error message reasons, this function is manually inlined in path_converter(). */ - _Py_IDENTIFIER(__fspath__); PyObject *func = NULL; PyObject *path_repr = NULL; diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c index 2e8be3706db914..747adfb9a04b0f 100644 --- a/Modules/pyexpat.c +++ b/Modules/pyexpat.c @@ -7,6 +7,9 @@ #include "pyexpat.h" + +_Py_IDENTIFIER(read); + /* Do not emit Clinic output to a file as that wreaks havoc with conditionally included methods. */ /*[clinic input] @@ -808,7 +811,6 @@ pyexpat_xmlparser_ParseFile(xmlparseobject *self, PyObject *file) { int rv = 1; PyObject *readmethod = NULL; - _Py_IDENTIFIER(read); readmethod = _PyObject_GetAttrId(file, &PyId_read); if (readmethod == NULL) { @@ -1054,7 +1056,7 @@ PyUnknownEncodingHandler(void *encodingHandlerData, const XML_Char *name, XML_Encoding *info) { - static unsigned char template_buffer[256] = {0}; + static unsigned char template_buffer[256] = {0}; /// Static is okay here (effectively immutable data). PyObject* u; int i; void *data; @@ -1628,6 +1630,8 @@ static int init_handler_descrs(void) return 0; } +static struct PyExpat_CAPI capi; + PyMODINIT_FUNC MODULE_INITFUNC(void) { @@ -1640,7 +1644,6 @@ MODULE_INITFUNC(void) PyObject *codes_dict; PyObject *rev_codes_dict; int res; - static struct PyExpat_CAPI capi; PyObject *capi_object; if (errmod_name == NULL) diff --git a/Modules/selectmodule.c b/Modules/selectmodule.c index 88130a1ecda0af..d19bf6595220d2 100644 --- a/Modules/selectmodule.c +++ b/Modules/selectmodule.c @@ -58,6 +58,9 @@ extern void bzero(void *, int); # define SOCKET int #endif + +_Py_IDENTIFIER(close); + /*[clinic input] module select class select.poll "pollObject *" "&poll_Type" @@ -1632,8 +1635,6 @@ select_epoll___exit___impl(pyEpoll_Object *self, PyObject *exc_type, PyObject *exc_value, PyObject *exc_tb) /*[clinic end generated code: output=c480f38ce361748e input=7ae81a5a4c1a98d8]*/ { - _Py_IDENTIFIER(close); - return _PyObject_CallMethodId((PyObject *)self, &PyId_close, NULL); } @@ -1823,9 +1824,14 @@ kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds) PyObject *pfd; static char *kwlist[] = {"ident", "filter", "flags", "fflags", "data", "udata", NULL}; - static const char fmt[] = "O|" - FILTER_FMT_UNIT FLAGS_FMT_UNIT FFLAGS_FMT_UNIT DATA_FMT_UNIT - UINTPTRT_FMT_UNIT ":kevent"; + static const char fmt[] = // Static is okay here (immutable data). + "O|" + FILTER_FMT_UNIT + FLAGS_FMT_UNIT + FFLAGS_FMT_UNIT + DATA_FMT_UNIT + UINTPTRT_FMT_UNIT + ":kevent"; EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c index c024542fe70923..41c3416c597ef2 100644 --- a/Modules/socketmodule.c +++ b/Modules/socketmodule.c @@ -2514,8 +2514,8 @@ static int cmsg_min_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t space) { size_t cmsg_offset; - static const size_t cmsg_len_end = (offsetof(struct cmsghdr, cmsg_len) + - sizeof(cmsgh->cmsg_len)); + static const size_t cmsg_len_end = // Static is okay here (immutable data). + (offsetof(struct cmsghdr, cmsg_len) + sizeof(cmsgh->cmsg_len)); /* Note that POSIX allows msg_controllen to be of signed type. */ if (cmsgh == NULL || msg->msg_control == NULL) @@ -4569,7 +4569,7 @@ sock_sendmsg_afalg(PySocketSockObject *self, PyObject *args, PyObject *kwds) struct sock_sendmsg ctx; Py_ssize_t controllen; void *controlbuf = NULL; - static char *keywords[] = {"msg", "op", "iv", "assoclen", "flags", 0}; + static char *kwlist[] = {"msg", "op", "iv", "assoclen", "flags", 0}; if (self->sock_family != AF_ALG) { PyErr_SetString(PyExc_OSError, @@ -4578,7 +4578,7 @@ sock_sendmsg_afalg(PySocketSockObject *self, PyObject *args, PyObject *kwds) } if (!PyArg_ParseTupleAndKeywords(args, kwds, - "|O$O!y*O!i:sendmsg_afalg", keywords, + "|O$O!y*O!i:sendmsg_afalg", kwlist, &data_arg, &PyLong_Type, &opobj, &iv, &PyLong_Type, &assoclenobj, &flags)) { @@ -5016,7 +5016,7 @@ sock_initobj(PyObject *self, PyObject *args, PyObject *kwds) PyObject *fdobj = NULL; SOCKET_T fd = INVALID_SOCKET; int family = -1, type = -1, proto = -1; - static char *keywords[] = {"family", "type", "proto", "fileno", 0}; + static char *kwlist[] = {"family", "type", "proto", "fileno", 0}; #ifndef MS_WINDOWS #ifdef SOCK_CLOEXEC int *atomic_flag_works = &sock_cloexec_works; @@ -5026,7 +5026,7 @@ sock_initobj(PyObject *self, PyObject *args, PyObject *kwds) #endif if (!PyArg_ParseTupleAndKeywords(args, kwds, - "|iiiO:socket", keywords, + "|iiiO:socket", kwlist, &family, &type, &proto, &fdobj)) return -1; @@ -6330,8 +6330,8 @@ socket_inet_ntop(PyObject *self, PyObject *args) static PyObject * socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs) { - static char* kwnames[] = {"host", "port", "family", "type", "proto", - "flags", 0}; + static char *kwlist[] = {"host", "port", "family", "type", "proto", + "flags", 0}; struct addrinfo hints, *res; struct addrinfo *res0 = NULL; PyObject *hobj = NULL; @@ -6346,7 +6346,7 @@ socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs) socktype = protocol = flags = 0; family = AF_UNSPEC; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iiii:getaddrinfo", - kwnames, &hobj, &pobj, &family, &socktype, + kwlist, &hobj, &pobj, &family, &socktype, &protocol, &flags)) { return NULL; } diff --git a/Modules/syslogmodule.c b/Modules/syslogmodule.c index b2ea73baa1be48..ab3347c5f16f42 100644 --- a/Modules/syslogmodule.c +++ b/Modules/syslogmodule.c @@ -115,11 +115,11 @@ syslog_openlog(PyObject * self, PyObject * args, PyObject *kwds) long logopt = 0; long facility = LOG_USER; PyObject *new_S_ident_o = NULL; - static char *keywords[] = {"ident", "logoption", "facility", 0}; + static char *kwlist[] = {"ident", "logoption", "facility", 0}; const char *ident = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Ull:openlog", kwlist, + &new_S_ident_o, &logopt, &facility)) return NULL; if (new_S_ident_o) { diff --git a/Modules/timemodule.c b/Modules/timemodule.c index f991f31ee15ed7..0812790e2fe291 100644 --- a/Modules/timemodule.c +++ b/Modules/timemodule.c @@ -50,6 +50,9 @@ #define SEC_TO_NS (1000 * 1000 * 1000) + +_Py_IDENTIFIER(_strptime_time); + /* Forward declarations */ static int pysleep(_PyTime_t); @@ -101,7 +104,7 @@ Return the current time in nanoseconds since the Epoch."); static int _PyTime_GetClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info) { - static int initialized = 0; + static int initialized = 0; // Static is okay here (process-global). clock_t ticks; if (!initialized) { @@ -855,7 +858,6 @@ static PyObject * time_strptime(PyObject *self, PyObject *args) { PyObject *module, *func, *result; - _Py_IDENTIFIER(_strptime_time); module = PyImport_ImportModuleNoBlock("_strptime"); if (!module) @@ -886,10 +888,10 @@ _asctime(struct tm *timeptr) { /* Inspired by Open Group reference implementation available at * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */ - static const char wday_name[7][4] = { + static const char wday_name[7][4] = { // Static is okay here (immutable data). "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; - static const char mon_name[12][4] = { + static const char mon_name[12][4] = { // Static is okay here (immutable data). "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; @@ -1219,7 +1221,7 @@ _PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info) struct tms t; if (times(&t) != (clock_t)-1) { - static long ticks_per_second = -1; + static long ticks_per_second = -1; // Static is okay here (process-global). if (ticks_per_second == -1) { long freq; @@ -1596,7 +1598,7 @@ init_timezone(PyObject *m) } PyModule_AddObject(m, "tzname", tzname_obj); #else // !HAVE_DECL_TZNAME - static const time_t YEAR = (365 * 24 + 6) * 3600; + static const time_t YEAR = (365 * 24 + 6) * 3600; // Static is okay here (immutable data). time_t t; struct tm p; time_t janzone_t, julyzone_t; diff --git a/Objects/abstract.c b/Objects/abstract.c index 68d06edfa60080..3523fbfdab2949 100644 --- a/Objects/abstract.c +++ b/Objects/abstract.c @@ -7,6 +7,18 @@ #include "longintrepr.h" +_Py_IDENTIFIER(__bases__); +_Py_IDENTIFIER(__class__); +_Py_IDENTIFIER(__class_getitem__); +_Py_IDENTIFIER(__format__); +_Py_IDENTIFIER(__instancecheck__); +_Py_IDENTIFIER(__length_hint__); +_Py_IDENTIFIER(__subclasscheck__); +_Py_IDENTIFIER(__trunc__); +_Py_IDENTIFIER(items); +_Py_IDENTIFIER(keys); +_Py_IDENTIFIER(values); + /* Shorthands to return certain errors */ @@ -87,7 +99,6 @@ PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue) { PyObject *hint, *result; Py_ssize_t res; - _Py_IDENTIFIER(__length_hint__); if (_PyObject_HasLen(o)) { res = PyObject_Length(o); if (res < 0) { @@ -173,7 +184,6 @@ PyObject_GetItem(PyObject *o, PyObject *key) if (PyType_Check(o)) { PyObject *meth, *result, *stack[1] = {key}; - _Py_IDENTIFIER(__class_getitem__); if (_PyObject_LookupAttrId(o, &PyId___class_getitem__, &meth) < 0) { return NULL; } @@ -700,7 +710,6 @@ PyObject_Format(PyObject *obj, PyObject *format_spec) PyObject *meth; PyObject *empty = NULL; PyObject *result = NULL; - _Py_IDENTIFIER(__format__); if (format_spec != NULL && !PyUnicode_Check(format_spec)) { PyErr_Format(PyExc_SystemError, @@ -1355,7 +1364,6 @@ PyNumber_Long(PyObject *o) PyNumberMethods *m; PyObject *trunc_func; Py_buffer view; - _Py_IDENTIFIER(__trunc__); if (o == NULL) { return null_error(); @@ -2227,7 +2235,6 @@ method_output_as_list(PyObject *o, _Py_Identifier *meth_id) PyObject * PyMapping_Keys(PyObject *o) { - _Py_IDENTIFIER(keys); if (o == NULL) { return null_error(); @@ -2241,7 +2248,6 @@ PyMapping_Keys(PyObject *o) PyObject * PyMapping_Items(PyObject *o) { - _Py_IDENTIFIER(items); if (o == NULL) { return null_error(); @@ -2255,7 +2261,6 @@ PyMapping_Items(PyObject *o) PyObject * PyMapping_Values(PyObject *o) { - _Py_IDENTIFIER(values); if (o == NULL) { return null_error(); @@ -2295,7 +2300,6 @@ PyMapping_Values(PyObject *o) static PyObject * abstract_get_bases(PyObject *cls) { - _Py_IDENTIFIER(__bases__); PyObject *bases; Py_ALLOW_RECURSION @@ -2365,7 +2369,6 @@ recursive_isinstance(PyObject *inst, PyObject *cls) { PyObject *icls; int retval; - _Py_IDENTIFIER(__class__); if (PyType_Check(cls)) { retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); @@ -2401,7 +2404,6 @@ recursive_isinstance(PyObject *inst, PyObject *cls) int PyObject_IsInstance(PyObject *inst, PyObject *cls) { - _Py_IDENTIFIER(__instancecheck__); PyObject *checker; /* Quick test for an exact match */ @@ -2476,7 +2478,6 @@ recursive_issubclass(PyObject *derived, PyObject *cls) int PyObject_IsSubclass(PyObject *derived, PyObject *cls) { - _Py_IDENTIFIER(__subclasscheck__); PyObject *checker; /* We know what type's __subclasscheck__ does. */ diff --git a/Objects/bytearrayobject.c b/Objects/bytearrayobject.c index eaf5dceb03a4ca..08e63415bca2f2 100644 --- a/Objects/bytearrayobject.c +++ b/Objects/bytearrayobject.c @@ -10,6 +10,10 @@ #include "bytesobject.h" #include "pystrhex.h" + +_Py_IDENTIFIER(__dict__); +_Py_IDENTIFIER(iter); + /*[clinic input] class bytearray "PyByteArrayObject *" "&PyByteArray_Type" [clinic start generated code]*/ @@ -2037,7 +2041,6 @@ static PyObject * _common_reduce(PyByteArrayObject *self, int proto) { PyObject *dict; - _Py_IDENTIFIER(__dict__); char *buf; dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__); @@ -2349,7 +2352,6 @@ PyDoc_STRVAR(length_hint_doc, static PyObject * bytearrayiter_reduce(bytesiterobject *it, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); if (it->it_seq != NULL) { return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter), it->it_seq, it->it_index); diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index b7c5b75283ee27..536e9da15fedfb 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -11,6 +11,10 @@ #include "pystrhex.h" #include + +_Py_IDENTIFIER(__bytes__); +_Py_IDENTIFIER(iter); + /*[clinic input] class bytes "PyBytesObject *" "&PyBytes_Type" [clinic start generated code]*/ @@ -543,7 +547,6 @@ static PyObject * format_obj(PyObject *v, const char **pbuf, Py_ssize_t *plen) { PyObject *func, *result; - _Py_IDENTIFIER(__bytes__); /* is it a bytes object? */ if (PyBytes_Check(v)) { *pbuf = PyBytes_AS_STRING(v); @@ -2536,7 +2539,6 @@ bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds) PyObject *func; Py_ssize_t size; static char *kwlist[] = {"source", "encoding", "errors", 0}; - _Py_IDENTIFIER(__bytes__); if (type != &PyBytes_Type) return bytes_subtype_new(type, args, kwds); @@ -3110,7 +3112,6 @@ PyDoc_STRVAR(length_hint_doc, static PyObject * striter_reduce(striterobject *it, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); if (it->it_seq != NULL) { return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter), it->it_seq, it->it_index); diff --git a/Objects/classobject.c b/Objects/classobject.c index 1ee897847fb03e..78700125712342 100644 --- a/Objects/classobject.c +++ b/Objects/classobject.c @@ -6,6 +6,9 @@ #include "pycore_pystate.h" #include "structmember.h" + +_Py_IDENTIFIER(getattr); + #define TP_DESCR_GET(t) ((t)->tp_descr_get) /* Free list for method objects to safe malloc/free overhead @@ -19,6 +22,7 @@ static int numfree = 0; _Py_IDENTIFIER(__name__); _Py_IDENTIFIER(__qualname__); +_Py_IDENTIFIER(__doc__); PyObject * PyMethod_Function(PyObject *im) @@ -79,7 +83,6 @@ method_reduce(PyMethodObject *im, PyObject *Py_UNUSED(ignored)) PyObject *self = PyMethod_GET_SELF(im); PyObject *func = PyMethod_GET_FUNCTION(im); PyObject *funcname; - _Py_IDENTIFIER(getattr); funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { @@ -116,13 +119,13 @@ static PyMemberDef method_memberlist[] = { static PyObject * method_get_doc(PyMethodObject *im, void *context) { - static PyObject *docstr; - if (docstr == NULL) { - docstr= PyUnicode_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - return PyObject_GetAttr(im->im_func, docstr); +// if (cached_str___doc__ == NULL) { +// cached_str___doc__= PyUnicode_InternFromString("__doc__"); +// if (cached_str___doc__ == NULL) +// return NULL; +// } +// return PyObject_GetAttr(im->im_func, cached_str___doc__); + return _PyObject_GetAttrId(im->im_func, &PyId___doc__); } static PyGetSetDef method_getset[] = { @@ -413,13 +416,7 @@ static PyMemberDef instancemethod_memberlist[] = { static PyObject * instancemethod_get_doc(PyObject *self, void *context) { - static PyObject *docstr; - if (docstr == NULL) { - docstr = PyUnicode_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr); + return _PyObject_GetAttrId(PyInstanceMethod_GET_FUNCTION(self), &PyId___doc__); } static PyGetSetDef instancemethod_getset[] = { diff --git a/Objects/codeobject.c b/Objects/codeobject.c index 62d7c5d329f07b..f19ecd97783402 100644 --- a/Objects/codeobject.c +++ b/Objects/codeobject.c @@ -226,22 +226,23 @@ PyCode_New(int argcount, int posonlyargcount, int kwonlyargcount, return co; } +static PyObject *cached_emptystring = NULL; +static PyObject *cached_nulltuple = NULL; + PyCodeObject * PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) { - static PyObject *emptystring = NULL; - static PyObject *nulltuple = NULL; PyObject *filename_ob = NULL; PyObject *funcname_ob = NULL; PyCodeObject *result = NULL; - if (emptystring == NULL) { - emptystring = PyBytes_FromString(""); - if (emptystring == NULL) + if (cached_emptystring == NULL) { + cached_emptystring = PyBytes_FromString(""); + if (cached_emptystring == NULL) goto failed; } - if (nulltuple == NULL) { - nulltuple = PyTuple_New(0); - if (nulltuple == NULL) + if (cached_nulltuple == NULL) { + cached_nulltuple = PyTuple_New(0); + if (cached_nulltuple == NULL) goto failed; } funcname_ob = PyUnicode_FromString(funcname); @@ -257,16 +258,16 @@ PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) 0, /* nlocals */ 0, /* stacksize */ 0, /* flags */ - emptystring, /* code */ - nulltuple, /* consts */ - nulltuple, /* names */ - nulltuple, /* varnames */ - nulltuple, /* freevars */ - nulltuple, /* cellvars */ + cached_emptystring, /* code */ + cached_nulltuple, /* consts */ + cached_nulltuple, /* names */ + cached_nulltuple, /* varnames */ + cached_nulltuple, /* freevars */ + cached_nulltuple, /* cellvars */ filename_ob, /* filename */ funcname_ob, /* name */ firstlineno, /* firstlineno */ - emptystring /* lnotab */ + cached_emptystring /* lnotab */ ); failed: diff --git a/Objects/complexobject.c b/Objects/complexobject.c index cae2bf11dc9b39..70c22e7b6f797d 100644 --- a/Objects/complexobject.c +++ b/Objects/complexobject.c @@ -8,6 +8,9 @@ #include "Python.h" #include "structmember.h" + +_Py_IDENTIFIER(__complex__); + /*[clinic input] class complex "PyComplexObject *" "&PyComplex_Type" [clinic start generated code]*/ @@ -277,7 +280,6 @@ static PyObject * try_complex_special_method(PyObject *op) { PyObject *f; - _Py_IDENTIFIER(__complex__); f = _PyObject_LookupSpecial(op, &PyId___complex__); if (f) { diff --git a/Objects/descrobject.c b/Objects/descrobject.c index 8f1a823768f393..01a54a0ada047f 100644 --- a/Objects/descrobject.c +++ b/Objects/descrobject.c @@ -6,6 +6,16 @@ #include "pycore_tupleobject.h" #include "structmember.h" /* Why is this not included in Python.h? */ + +_Py_IDENTIFIER(__doc__); +_Py_IDENTIFIER(__qualname__); +_Py_IDENTIFIER(copy); +_Py_IDENTIFIER(get); +_Py_IDENTIFIER(getattr); +_Py_IDENTIFIER(items); +_Py_IDENTIFIER(keys); +_Py_IDENTIFIER(values); + /*[clinic input] class mappingproxy "mappingproxyobject *" "&PyDictProxy_Type" class property "propertyobject *" "&PyProperty_Type" @@ -411,7 +421,6 @@ static PyObject * calculate_qualname(PyDescrObject *descr) { PyObject *type_qualname, *res; - _Py_IDENTIFIER(__qualname__); if (descr->d_name == NULL || !PyUnicode_Check(descr->d_name)) { PyErr_SetString(PyExc_TypeError, @@ -448,7 +457,6 @@ descr_get_qualname(PyDescrObject *descr, void *Py_UNUSED(ignored)) static PyObject * descr_reduce(PyDescrObject *descr, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(getattr); return Py_BuildValue("N(OO)", _PyEval_GetBuiltinId(&PyId_getattr), PyDescr_TYPE(descr), PyDescr_NAME(descr)); } @@ -852,7 +860,6 @@ static PyObject * mappingproxy_get(mappingproxyobject *pp, PyObject *args) { PyObject *key, *def = Py_None; - _Py_IDENTIFIER(get); if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) return NULL; @@ -863,28 +870,24 @@ mappingproxy_get(mappingproxyobject *pp, PyObject *args) static PyObject * mappingproxy_keys(mappingproxyobject *pp, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(keys); return _PyObject_CallMethodId(pp->mapping, &PyId_keys, NULL); } static PyObject * mappingproxy_values(mappingproxyobject *pp, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(values); return _PyObject_CallMethodId(pp->mapping, &PyId_values, NULL); } static PyObject * mappingproxy_items(mappingproxyobject *pp, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(items); return _PyObject_CallMethodId(pp->mapping, &PyId_items, NULL); } static PyObject * mappingproxy_copy(mappingproxyobject *pp, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(copy); return _PyObject_CallMethodId(pp->mapping, &PyId_copy, NULL); } @@ -1078,7 +1081,6 @@ wrapper_repr(wrapperobject *wp) static PyObject * wrapper_reduce(wrapperobject *wp, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(getattr); return Py_BuildValue("N(OO)", _PyEval_GetBuiltinId(&PyId_getattr), wp->self, PyDescr_NAME(wp->descr)); } @@ -1461,7 +1463,6 @@ property_init_impl(propertyobject *self, PyObject *fget, PyObject *fset, /* if no docstring given and the getter has one, use that one */ if ((doc == NULL || doc == Py_None) && fget != NULL) { - _Py_IDENTIFIER(__doc__); PyObject *get_doc = _PyObject_GetAttrId(fget, &PyId___doc__); if (get_doc) { if (Py_TYPE(self) == &PyProperty_Type) { diff --git a/Objects/dictobject.c b/Objects/dictobject.c index 88ac1a9dcd0fb5..ea435cf5a586af 100644 --- a/Objects/dictobject.c +++ b/Objects/dictobject.c @@ -116,6 +116,15 @@ converting the dict to the combined table. #include "dict-common.h" #include "stringlib/eq.h" /* to get unicode_eq() */ + +_Py_IDENTIFIER(__missing__); +_Py_IDENTIFIER(difference_update); +_Py_IDENTIFIER(intersection_update); +_Py_IDENTIFIER(iter); +_Py_IDENTIFIER(keys); +_Py_IDENTIFIER(symmetric_difference_update); +_Py_IDENTIFIER(update); + /*[clinic input] class dict "PyDictObject *" "&PyDict_Type" [clinic start generated code]*/ @@ -2109,7 +2118,6 @@ dict_subscript(PyDictObject *mp, PyObject *key) if (!PyDict_CheckExact(mp)) { /* Look up __missing__ method if we're a subclass. */ PyObject *missing, *res; - _Py_IDENTIFIER(__missing__); missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__); if (missing != NULL) { res = PyObject_CallFunctionObjArgs(missing, @@ -2317,7 +2325,6 @@ dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, result = -1; } else if (arg != NULL) { - _Py_IDENTIFIER(keys); PyObject *func; if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) { result = -1; @@ -3910,7 +3917,6 @@ dict___reversed___impl(PyDictObject *self) static PyObject * dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); /* copy the iterator state */ dictiterobject tmp = *di; Py_XINCREF(tmp.di_dict); @@ -4154,7 +4160,6 @@ dictviews_sub(PyObject* self, PyObject *other) { PyObject *result = PySet_New(self); PyObject *tmp; - _Py_IDENTIFIER(difference_update); if (result == NULL) return NULL; @@ -4174,7 +4179,6 @@ _PyDictView_Intersect(PyObject* self, PyObject *other) { PyObject *result = PySet_New(self); PyObject *tmp; - _Py_IDENTIFIER(intersection_update); if (result == NULL) return NULL; @@ -4194,7 +4198,6 @@ dictviews_or(PyObject* self, PyObject *other) { PyObject *result = PySet_New(self); PyObject *tmp; - _Py_IDENTIFIER(update); if (result == NULL) return NULL; @@ -4214,7 +4217,6 @@ dictviews_xor(PyObject* self, PyObject *other) { PyObject *result = PySet_New(self); PyObject *tmp; - _Py_IDENTIFIER(symmetric_difference_update); if (result == NULL) return NULL; diff --git a/Objects/enumobject.c b/Objects/enumobject.c index d993a5063fdf60..4429e654c7a352 100644 --- a/Objects/enumobject.c +++ b/Objects/enumobject.c @@ -4,6 +4,9 @@ #include "clinic/enumobject.c.h" + +_Py_IDENTIFIER(__reversed__); + /*[clinic input] class enumerate "enumobject *" "&PyEnum_Type" class reversed "reversedobject *" "&PyReversed_Type" @@ -273,7 +276,6 @@ reversed_new_impl(PyTypeObject *type, PyObject *seq) Py_ssize_t n; PyObject *reversed_meth; reversedobject *ro; - _Py_IDENTIFIER(__reversed__); reversed_meth = _PyObject_LookupSpecial(seq, &PyId___reversed__); if (reversed_meth == Py_None) { diff --git a/Objects/exceptions.c b/Objects/exceptions.c index b40ecb78d456ef..337d611d84f1ee 100644 --- a/Objects/exceptions.c +++ b/Objects/exceptions.c @@ -13,6 +13,9 @@ #include "osdefs.h" +_Py_IDENTIFIER(name); +_Py_IDENTIFIER(path); + /* Compatibility aliases */ PyObject *PyExc_EnvironmentError = NULL; PyObject *PyExc_IOError = NULL; @@ -699,8 +702,6 @@ ImportError_getstate(PyImportErrorObject *self) { PyObject *dict = ((PyBaseExceptionObject *)self)->dict; if (self->name || self->path) { - _Py_IDENTIFIER(name); - _Py_IDENTIFIER(path); dict = dict ? PyDict_Copy(dict) : PyDict_New(); if (dict == NULL) return NULL; @@ -2949,6 +2950,9 @@ _set_legacy_print_statement_msg(PySyntaxErrorObject *self, Py_ssize_t start) return 1; } +static PyObject *cached_print_prefix = NULL; +static PyObject *cached_exec_prefix = NULL; + static int _check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start) { @@ -2957,8 +2961,6 @@ _check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start) * 0: nothing happened * 1: the check triggered & the error message was changed */ - static PyObject *print_prefix = NULL; - static PyObject *exec_prefix = NULL; Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text), match; int kind = PyUnicode_KIND(self->text); void *data = PyUnicode_DATA(self->text); @@ -2976,13 +2978,13 @@ _check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start) } /* Check for legacy print statements */ - if (print_prefix == NULL) { - print_prefix = PyUnicode_InternFromString("print "); - if (print_prefix == NULL) { + if (cached_print_prefix == NULL) { + cached_print_prefix = PyUnicode_InternFromString("print "); + if (cached_print_prefix == NULL) { return -1; } } - match = PyUnicode_Tailmatch(self->text, print_prefix, + match = PyUnicode_Tailmatch(self->text, cached_print_prefix, start, text_len, -1); if (match == -1) { return -1; @@ -2992,13 +2994,14 @@ _check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start) } /* Check for legacy exec statements */ - if (exec_prefix == NULL) { - exec_prefix = PyUnicode_InternFromString("exec "); - if (exec_prefix == NULL) { + if (cached_exec_prefix == NULL) { + cached_exec_prefix = PyUnicode_InternFromString("exec "); + if (cached_exec_prefix == NULL) { return -1; } } - match = PyUnicode_Tailmatch(self->text, exec_prefix, start, text_len, -1); + match = PyUnicode_Tailmatch(self->text, cached_exec_prefix, + start, text_len, -1); if (match == -1) { return -1; } diff --git a/Objects/fileobject.c b/Objects/fileobject.c index 39c7c109979a48..fbf5eae6b25bcb 100644 --- a/Objects/fileobject.c +++ b/Objects/fileobject.c @@ -24,6 +24,11 @@ extern "C" { #endif +_Py_IDENTIFIER(open); +_Py_IDENTIFIER(readline); +_Py_IDENTIFIER(write); +_Py_IDENTIFIER(fileno); + /* External C interface */ PyObject * @@ -31,7 +36,6 @@ PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const c const char *errors, const char *newline, int closefd) { PyObject *io, *stream; - _Py_IDENTIFIER(open); io = PyImport_ImportModule("io"); if (io == NULL) @@ -50,7 +54,6 @@ PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const c PyObject * PyFile_GetLine(PyObject *f, int n) { - _Py_IDENTIFIER(readline); PyObject *result; if (f == NULL) { @@ -116,7 +119,6 @@ int PyFile_WriteObject(PyObject *v, PyObject *f, int flags) { PyObject *writer, *value, *result; - _Py_IDENTIFIER(write); if (f == NULL) { PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); @@ -178,7 +180,6 @@ PyObject_AsFileDescriptor(PyObject *o) { int fd; PyObject *meth; - _Py_IDENTIFIER(fileno); if (PyLong_Check(o)) { fd = _PyLong_AsInt(o); diff --git a/Objects/funcobject.c b/Objects/funcobject.c index e8e2d2e15ccabf..ec97824b91105e 100644 --- a/Objects/funcobject.c +++ b/Objects/funcobject.c @@ -9,18 +9,13 @@ #include "code.h" #include "structmember.h" +_Py_IDENTIFIER(__name__); + PyObject * PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname) { PyFunctionObject *op; PyObject *doc, *consts, *module; - static PyObject *__name__ = NULL; - - if (__name__ == NULL) { - __name__ = PyUnicode_InternFromString("__name__"); - if (__name__ == NULL) - return NULL; - } op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type); if (op == NULL) @@ -54,7 +49,7 @@ PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname /* __module__: If module name is in globals, use it. Otherwise, use None. */ - module = PyDict_GetItemWithError(globals, __name__); + module = _PyDict_GetItemIdWithError(globals, &PyId___name__); if (module) { Py_INCREF(module); op->func_module = module; diff --git a/Objects/genobject.c b/Objects/genobject.c index e2def38af541a5..451cac423fa267 100644 --- a/Objects/genobject.c +++ b/Objects/genobject.c @@ -7,6 +7,10 @@ #include "structmember.h" #include "opcode.h" + +_Py_IDENTIFIER(close); +_Py_IDENTIFIER(throw); + static PyObject *gen_close(PyGenObject *, PyObject *); static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *); static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *); @@ -304,7 +308,6 @@ static int gen_close_iter(PyObject *yf) { PyObject *retval = NULL; - _Py_IDENTIFIER(close); if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) { retval = gen_close((PyGenObject *)yf, NULL); @@ -399,7 +402,6 @@ _gen_throw(PyGenObject *gen, int close_on_genexit, PyObject *typ, PyObject *val, PyObject *tb) { PyObject *yf = _PyGen_yf(gen); - _Py_IDENTIFIER(throw); if (yf) { PyObject *ret; diff --git a/Objects/iterobject.c b/Objects/iterobject.c index 5bee1e21e65e51..a231aeb9248014 100644 --- a/Objects/iterobject.c +++ b/Objects/iterobject.c @@ -5,6 +5,9 @@ #include "pycore_pymem.h" #include "pycore_pystate.h" + +_Py_IDENTIFIER(iter); + typedef struct { PyObject_HEAD Py_ssize_t it_index; @@ -104,7 +107,6 @@ PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list( static PyObject * iter_reduce(seqiterobject *it, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); if (it->it_seq != NULL) return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter), it->it_seq, it->it_index); @@ -244,7 +246,6 @@ calliter_iternext(calliterobject *it) static PyObject * calliter_reduce(calliterobject *it, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); if (it->it_callable != NULL && it->it_sentinel != NULL) return Py_BuildValue("N(OO)", _PyEval_GetBuiltinId(&PyId_iter), it->it_callable, it->it_sentinel); diff --git a/Objects/listobject.c b/Objects/listobject.c index 08b3e89a957fb9..06d04d0671a28a 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -12,6 +12,10 @@ #include /* For size_t */ #endif + +_Py_IDENTIFIER(iter); +_Py_IDENTIFIER(reversed); + /*[clinic input] class list "PyListObject *" "&PyList_Type" [clinic start generated code]*/ @@ -152,12 +156,15 @@ _PyList_DebugMallocStats(FILE *out) numfree, sizeof(PyListObject)); } +#ifdef SHOW_ALLOC_COUNT +static int initialized = 0; +#endif + PyObject * PyList_New(Py_ssize_t size) { PyListObject *op; #ifdef SHOW_ALLOC_COUNT - static int initialized = 0; if (!initialized) { Py_AtExit(show_alloc); initialized = 1; @@ -3348,8 +3355,6 @@ listreviter_setstate(listreviterobject *it, PyObject *state) static PyObject * listiter_reduce_general(void *_it, int forward) { - _Py_IDENTIFIER(iter); - _Py_IDENTIFIER(reversed); PyObject *list; /* the objects are not the same, index is of different types! */ diff --git a/Objects/longobject.c b/Objects/longobject.c index 9fb1fb02c276bd..d7e77e45e97a1f 100644 --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -2439,9 +2439,9 @@ digit beyond the first. const char *scan, *lastdigit; char prev = 0; - static double log_base_BASE[37] = {0.0e0,}; - static int convwidth_base[37] = {0,}; - static twodigits convmultmax_base[37] = {0,}; + static double log_base_BASE[37] = {0.0e0,}; // Static is okay here (global cache). + static int convwidth_base[37] = {0,}; // Static is okay here (global cache). + static twodigits convmultmax_base[37] = {0,}; // Static is okay here (global cache). if (log_base_BASE[base] == 0.0) { twodigits convmax = base; @@ -2918,7 +2918,9 @@ _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e) /* Correction term for round-half-to-even rounding. For a digit x, "x + half_even_correction[x & 7]" gives x rounded to the nearest multiple of 4, rounding ties to a multiple of 8. */ - static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1}; + static const int half_even_correction[8] = { // Static is okay here (immutable data). + 0, -1, -2, 1, 0, -1, 2, 1 + }; a_size = Py_ABS(Py_SIZE(a)); if (a_size == 0) { diff --git a/Objects/methodobject.c b/Objects/methodobject.c index 9fed3fca99be9f..0feeda4428d2d9 100644 --- a/Objects/methodobject.c +++ b/Objects/methodobject.c @@ -7,6 +7,11 @@ #include "pycore_pystate.h" #include "structmember.h" + +_Py_IDENTIFIER(__qualname__); +_Py_IDENTIFIER(getattr); + + /* Free list for method objects to safe malloc/free overhead * The m_self element is used to chain the objects. */ @@ -104,8 +109,6 @@ meth_dealloc(PyCFunctionObject *m) static PyObject * meth_reduce(PyCFunctionObject *m, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(getattr); - if (m->m_self == NULL || PyModule_Check(m->m_self)) return PyUnicode_FromString(m->m_ml->ml_name); @@ -148,7 +151,6 @@ meth_get__qualname__(PyCFunctionObject *m, void *closure) Otherwise return type(m.__self__).__qualname__ + '.' + m.__name__ (e.g. [].append.__qualname__ == 'list.append') */ PyObject *type, *type_qualname, *res; - _Py_IDENTIFIER(__qualname__); if (m->m_self == NULL || PyModule_Check(m->m_self)) return PyUnicode_FromString(m->m_ml->ml_name); diff --git a/Objects/moduleobject.c b/Objects/moduleobject.c index e570107cedfba5..9ec5bc46b3639d 100644 --- a/Objects/moduleobject.c +++ b/Objects/moduleobject.c @@ -5,6 +5,18 @@ #include "pycore_pystate.h" #include "structmember.h" + +_Py_IDENTIFIER(__dict__); +_Py_IDENTIFIER(__dir__); +_Py_IDENTIFIER(__doc__); +_Py_IDENTIFIER(__file__); +_Py_IDENTIFIER(__getattr__); +_Py_IDENTIFIER(__loader__); +_Py_IDENTIFIER(__name__); +_Py_IDENTIFIER(__package__); +_Py_IDENTIFIER(__spec__); +_Py_IDENTIFIER(_initializing); + static Py_ssize_t max_module_number; typedef struct { @@ -58,12 +70,6 @@ static int module_init_dict(PyModuleObject *mod, PyObject *md_dict, PyObject *name, PyObject *doc) { - _Py_IDENTIFIER(__name__); - _Py_IDENTIFIER(__doc__); - _Py_IDENTIFIER(__package__); - _Py_IDENTIFIER(__loader__); - _Py_IDENTIFIER(__spec__); - if (md_dict == NULL) return -1; if (doc == NULL) @@ -458,7 +464,6 @@ int PyModule_SetDocString(PyObject *m, const char *doc) { PyObject *v; - _Py_IDENTIFIER(__doc__); v = PyUnicode_FromString(doc); if (v == NULL || _PyObject_SetAttrId(m, &PyId___doc__, v) != 0) { @@ -485,7 +490,6 @@ PyModule_GetDict(PyObject *m) PyObject* PyModule_GetNameObject(PyObject *m) { - _Py_IDENTIFIER(__name__); PyObject *d; PyObject *name; if (!PyModule_Check(m)) { @@ -517,7 +521,6 @@ PyModule_GetName(PyObject *m) PyObject* PyModule_GetFilenameObject(PyObject *m) { - _Py_IDENTIFIER(__file__); PyObject *d; PyObject *fileobj; if (!PyModule_Check(m)) { @@ -709,7 +712,6 @@ int _PyModuleSpec_IsInitializing(PyObject *spec) { if (spec != NULL) { - _Py_IDENTIFIER(_initializing); PyObject *value = _PyObject_GetAttrId(spec, &PyId__initializing); if (value != NULL) { int initializing = PyObject_IsTrue(value); @@ -733,16 +735,13 @@ module_getattro(PyModuleObject *m, PyObject *name) } PyErr_Clear(); if (m->md_dict) { - _Py_IDENTIFIER(__getattr__); getattr = _PyDict_GetItemId(m->md_dict, &PyId___getattr__); if (getattr) { PyObject* stack[1] = {name}; return _PyObject_FastCall(getattr, stack, 1); } - _Py_IDENTIFIER(__name__); mod_name = _PyDict_GetItemId(m->md_dict, &PyId___name__); if (mod_name && PyUnicode_Check(mod_name)) { - _Py_IDENTIFIER(__spec__); Py_INCREF(mod_name); PyObject *spec = _PyDict_GetItemId(m->md_dict, &PyId___spec__); Py_XINCREF(spec); @@ -795,8 +794,6 @@ module_clear(PyModuleObject *m) static PyObject * module_dir(PyObject *self, PyObject *args) { - _Py_IDENTIFIER(__dict__); - _Py_IDENTIFIER(__dir__); PyObject *result = NULL; PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__); diff --git a/Objects/obmalloc.c b/Objects/obmalloc.c index bd15bcf1363bde..9966294b2f2102 100644 --- a/Objects/obmalloc.c +++ b/Objects/obmalloc.c @@ -1150,6 +1150,8 @@ _Py_GetAllocatedBlocks(void) } +static int debug_stats = -1; + /* Allocate a new arena. If we run out of memory, return NULL. Else * allocate a new arena, and return the address of an arena_object * describing the new arena. It's expected that the caller will set @@ -1161,7 +1163,6 @@ new_arena(void) struct arena_object* arenaobj; uint excess; /* number of bytes above pool alignment */ void *address; - static int debug_stats = -1; if (debug_stats == -1) { const char *opt = Py_GETENV("PYTHONMALLOCSTATS"); diff --git a/Objects/odictobject.c b/Objects/odictobject.c index 773827d85b3aa8..1d33c0bd401f10 100644 --- a/Objects/odictobject.c +++ b/Objects/odictobject.c @@ -471,6 +471,12 @@ Potential Optimizations #include "dict-common.h" #include + +_Py_IDENTIFIER(__dict__); +_Py_IDENTIFIER(items); +_Py_IDENTIFIER(iter); +_Py_IDENTIFIER(keys); + #include "clinic/odictobject.c.h" /*[clinic input] @@ -895,8 +901,6 @@ PyDoc_STRVAR(odict_reduce__doc__, "Return state information for pickling"); static PyObject * odict_reduce(register PyODictObject *od, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(__dict__); - _Py_IDENTIFIER(items); PyObject *dict = NULL, *result = NULL; PyObject *items_iter, *items, *args = NULL; @@ -1375,7 +1379,6 @@ static PyObject * odict_repr(PyODictObject *self) { int i; - _Py_IDENTIFIER(items); PyObject *pieces = NULL, *result = NULL; if (PyODict_SIZE(self) == 0) @@ -1795,7 +1798,6 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling"); static PyObject * odictiter_reduce(odictiterobject *di, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); /* copy the iterator state */ odictiterobject tmp = *di; Py_XINCREF(tmp.di_odict); @@ -2195,8 +2197,6 @@ mutablemapping_update(PyObject *self, PyObject *args, PyObject *kwargs) { int res = 0; Py_ssize_t len; - _Py_IDENTIFIER(items); - _Py_IDENTIFIER(keys); /* first handle args, if any */ assert(args == NULL || PyTuple_Check(args)); diff --git a/Objects/rangeobject.c b/Objects/rangeobject.c index ac868f6951c29c..46727b13d1ab94 100644 --- a/Objects/rangeobject.c +++ b/Objects/rangeobject.c @@ -3,6 +3,9 @@ #include "Python.h" #include "structmember.h" + +_Py_IDENTIFIER(iter); + /* Support objects whose length is > PY_SSIZE_T_MAX. This could be sped up for small PyLongs if they fit in a Py_ssize_t. @@ -742,7 +745,6 @@ PyDoc_STRVAR(length_hint_doc, static PyObject * rangeiter_reduce(rangeiterobject *r, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); PyObject *start=NULL, *stop=NULL, *step=NULL; PyObject *range; @@ -900,7 +902,6 @@ longrangeiter_len(longrangeiterobject *r, PyObject *no_args) static PyObject * longrangeiter_reduce(longrangeiterobject *r, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); PyObject *product, *stop=NULL; PyObject *range; diff --git a/Objects/setobject.c b/Objects/setobject.c index 82e9639d2884ca..060d6dd1ff18b2 100644 --- a/Objects/setobject.c +++ b/Objects/setobject.c @@ -36,6 +36,10 @@ #include "pycore_pystate.h" #include "structmember.h" + +_Py_IDENTIFIER(__dict__); +_Py_IDENTIFIER(iter); + /* Object used as dummy key to fill deleted entries */ static PyObject _dummy_struct; @@ -842,7 +846,6 @@ static PyObject *setiter_iternext(setiterobject *si); static PyObject * setiter_reduce(setiterobject *si, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); /* copy the iterator state */ setiterobject tmp = *si; Py_XINCREF(tmp.si_set); @@ -1954,7 +1957,6 @@ static PyObject * set_reduce(PySetObject *so, PyObject *Py_UNUSED(ignored)) { PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL; - _Py_IDENTIFIER(__dict__); keys = PySequence_List((PyObject *)so); if (keys == NULL) diff --git a/Objects/tupleobject.c b/Objects/tupleobject.c index 9f0fc1cc2c3fd4..efaaa1f777d996 100644 --- a/Objects/tupleobject.c +++ b/Objects/tupleobject.c @@ -6,6 +6,9 @@ #include "pycore_pystate.h" #include "pycore_accu.h" + +_Py_IDENTIFIER(iter); + /*[clinic input] class tuple "PyTupleObject *" "&PyTuple_Type" [clinic start generated code]*/ @@ -1025,7 +1028,6 @@ PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list( static PyObject * tupleiter_reduce(tupleiterobject *it, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); if (it->it_seq) return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter), it->it_seq, it->it_index); diff --git a/Objects/typeobject.c b/Objects/typeobject.c index bfbd320b1f54d8..238785a4363a45 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -8,6 +8,7 @@ #include + /*[clinic input] class type "PyTypeObject *" "&PyType_Type" class object "PyObject *" "&PyBaseObject_Type" @@ -55,22 +56,59 @@ static size_t method_cache_collisions = 0; /* alphabetical order */ _Py_IDENTIFIER(__abstractmethods__); +_Py_IDENTIFIER(__await__); +_Py_IDENTIFIER(__aiter__); +_Py_IDENTIFIER(__anext__); +_Py_IDENTIFIER(__bases__); +_Py_IDENTIFIER(__bool__); +_Py_IDENTIFIER(__call__); _Py_IDENTIFIER(__class__); +_Py_IDENTIFIER(__classcell__); _Py_IDENTIFIER(__class_getitem__); +_Py_IDENTIFIER(__contains__); +_Py_IDENTIFIER(__del__); +_Py_IDENTIFIER(__delattr__); +_Py_IDENTIFIER(__delete__); _Py_IDENTIFIER(__delitem__); _Py_IDENTIFIER(__dict__); _Py_IDENTIFIER(__doc__); +_Py_IDENTIFIER(__eq__); +_Py_IDENTIFIER(__get__); +_Py_IDENTIFIER(__getattr__); _Py_IDENTIFIER(__getattribute__); _Py_IDENTIFIER(__getitem__); +_Py_IDENTIFIER(__getnewargs__); +_Py_IDENTIFIER(__getnewargs_ex__); +_Py_IDENTIFIER(__getstate__); _Py_IDENTIFIER(__hash__); +_Py_IDENTIFIER(__index__); +_Py_IDENTIFIER(__init__); _Py_IDENTIFIER(__init_subclass__); +_Py_IDENTIFIER(__ipow__); +_Py_IDENTIFIER(__iter__); _Py_IDENTIFIER(__len__); _Py_IDENTIFIER(__module__); +_Py_IDENTIFIER(__mro_entries__); _Py_IDENTIFIER(__name__); _Py_IDENTIFIER(__new__); +_Py_IDENTIFIER(__newobj__); +_Py_IDENTIFIER(__newobj_ex__); +_Py_IDENTIFIER(__next__); +_Py_IDENTIFIER(__pow__); +_Py_IDENTIFIER(__qualname__); +_Py_IDENTIFIER(__reduce__); +_Py_IDENTIFIER(__repr__); +_Py_IDENTIFIER(__set__); _Py_IDENTIFIER(__set_name__); +_Py_IDENTIFIER(__setattr__); _Py_IDENTIFIER(__setitem__); +_Py_IDENTIFIER(__slots__); +_Py_IDENTIFIER(__slotnames__); +_Py_IDENTIFIER(_slotnames); _Py_IDENTIFIER(builtins); +_Py_IDENTIFIER(copyreg); +_Py_IDENTIFIER(items); +_Py_IDENTIFIER(mro); static PyObject * slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds); @@ -1849,7 +1887,6 @@ mro_invoke(PyTypeObject *type) int custom = (Py_TYPE(type) != &PyType_Type); if (custom) { - _Py_IDENTIFIER(mro); int unbound; PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro, &unbound); @@ -2296,9 +2333,6 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) PyMemberDef *mp; Py_ssize_t i, nbases, nslots, slotoffset, name_size; int j, may_add_dict, may_add_weak, add_dict, add_weak; - _Py_IDENTIFIER(__qualname__); - _Py_IDENTIFIER(__slots__); - _Py_IDENTIFIER(__classcell__); assert(args != NULL && PyTuple_Check(args)); assert(kwds == NULL || PyDict_Check(kwds)); @@ -2341,7 +2375,6 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) nbases = 1; } else { - _Py_IDENTIFIER(__mro_entries__); for (i = 0; i < nbases; i++) { tmp = PyTuple_GET_ITEM(bases, i); if (PyType_Check(tmp)) { @@ -3382,7 +3415,6 @@ merge_class_dict(PyObject *dict, PyObject *aclass) { PyObject *classdict; PyObject *bases; - _Py_IDENTIFIER(__bases__); assert(PyDict_Check(dict)); assert(aclass); @@ -4048,7 +4080,6 @@ import_copyreg(void) { PyObject *copyreg_str; PyObject *copyreg_module; - _Py_IDENTIFIER(copyreg); copyreg_str = _PyUnicode_FromId(&PyId_copyreg); if (copyreg_str == NULL) { @@ -4074,8 +4105,6 @@ _PyType_GetSlotNames(PyTypeObject *cls) { PyObject *copyreg; PyObject *slotnames; - _Py_IDENTIFIER(__slotnames__); - _Py_IDENTIFIER(_slotnames); assert(PyType_Check(cls)); @@ -4127,7 +4156,6 @@ _PyObject_GetState(PyObject *obj, int required) { PyObject *state; PyObject *getstate; - _Py_IDENTIFIER(__getstate__); if (_PyObject_LookupAttrId(obj, &PyId___getstate__, &getstate) < 0) { return NULL; @@ -4267,8 +4295,6 @@ static int _PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs) { PyObject *getnewargs, *getnewargs_ex; - _Py_IDENTIFIER(__getnewargs_ex__); - _Py_IDENTIFIER(__getnewargs__); if (args == NULL || kwargs == NULL) { PyErr_BadInternalCall(); @@ -4384,7 +4410,6 @@ _PyObject_GetItemsIter(PyObject *obj, PyObject **listitems, } else { PyObject *items; - _Py_IDENTIFIER(items); items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL); if (items == NULL) { @@ -4430,7 +4455,6 @@ reduce_newobj(PyObject *obj) } hasargs = (args != NULL); if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) { - _Py_IDENTIFIER(__newobj__); PyObject *cls; Py_ssize_t i, n; @@ -4459,8 +4483,6 @@ reduce_newobj(PyObject *obj) Py_XDECREF(args); } else if (args != NULL) { - _Py_IDENTIFIER(__newobj_ex__); - newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__); Py_DECREF(copyreg); if (newobj == NULL) { @@ -4552,6 +4574,8 @@ object___reduce___impl(PyObject *self) return _common_reduce(self, 0); } +static PyObject *objreduce = NULL; + /*[clinic input] object.__reduce_ex__ @@ -4565,9 +4589,7 @@ static PyObject * object___reduce_ex___impl(PyObject *self, int protocol) /*[clinic end generated code: output=2e157766f6b50094 input=f326b43fb8a4c5ff]*/ { - static PyObject *objreduce; PyObject *reduce, *res; - _Py_IDENTIFIER(__reduce__); if (objreduce == NULL) { objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict, @@ -4975,7 +4997,6 @@ static int overrides_hash(PyTypeObject *type) { PyObject *dict = type->tp_dict; - _Py_IDENTIFIER(__eq__); assert(dict != NULL); if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL) @@ -6174,7 +6195,6 @@ slot_sq_contains(PyObject *self, PyObject *value) { PyObject *func, *res; int result = -1, unbound; - _Py_IDENTIFIER(__contains__); func = lookup_maybe_method(self, &PyId___contains__, &unbound); if (func == Py_None) { @@ -6241,8 +6261,6 @@ SLOT1BINFULL(slot_nb_power_binary, slot_nb_power, static PyObject * slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus) { - _Py_IDENTIFIER(__pow__); - if (modulus == Py_None) return slot_nb_power_binary(self, other); /* Three-arg power doesn't use __rpow__. But ternary_op @@ -6266,7 +6284,6 @@ slot_nb_bool(PyObject *self) PyObject *func, *value; int result, unbound; int using_len = 0; - _Py_IDENTIFIER(__bool__); func = lookup_maybe_method(self, &PyId___bool__, &unbound); if (func == NULL) { @@ -6317,7 +6334,6 @@ slot_nb_bool(PyObject *self) static PyObject * slot_nb_index(PyObject *self) { - _Py_IDENTIFIER(__index__); return call_method(self, &PyId___index__, NULL, 0); } @@ -6341,7 +6357,6 @@ static PyObject * slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) { PyObject *stack[1] = {arg1}; - _Py_IDENTIFIER(__ipow__); return call_method(self, &PyId___ipow__, stack, 1); } SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *) @@ -6359,7 +6374,6 @@ static PyObject * slot_tp_repr(PyObject *self) { PyObject *func, *res; - _Py_IDENTIFIER(__repr__); int unbound; func = lookup_maybe_method(self, &PyId___repr__, &unbound); @@ -6426,7 +6440,6 @@ slot_tp_hash(PyObject *self) static PyObject * slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds) { - _Py_IDENTIFIER(__call__); int unbound; PyObject *meth = lookup_method(self, &PyId___call__, &unbound); PyObject *res; @@ -6486,7 +6499,6 @@ slot_tp_getattr_hook(PyObject *self, PyObject *name) { PyTypeObject *tp = Py_TYPE(self); PyObject *getattr, *getattribute, *res; - _Py_IDENTIFIER(__getattr__); /* speed hack: we could use lookup_maybe, but that would resolve the method fully for each attribute lookup for classes with @@ -6529,8 +6541,6 @@ slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value) { PyObject *stack[2]; PyObject *res; - _Py_IDENTIFIER(__delattr__); - _Py_IDENTIFIER(__setattr__); stack[0] = name; if (value == NULL) { @@ -6578,7 +6588,6 @@ slot_tp_iter(PyObject *self) { int unbound; PyObject *func, *res; - _Py_IDENTIFIER(__iter__); func = lookup_maybe_method(self, &PyId___iter__, &unbound); if (func == Py_None) { @@ -6610,7 +6619,6 @@ slot_tp_iter(PyObject *self) static PyObject * slot_tp_iternext(PyObject *self) { - _Py_IDENTIFIER(__next__); return call_method(self, &PyId___next__, NULL, 0); } @@ -6619,7 +6627,6 @@ slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type) { PyTypeObject *tp = Py_TYPE(self); PyObject *get; - _Py_IDENTIFIER(__get__); get = _PyType_LookupId(tp, &PyId___get__); if (get == NULL) { @@ -6641,8 +6648,6 @@ slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value) { PyObject* stack[2]; PyObject *res; - _Py_IDENTIFIER(__delete__); - _Py_IDENTIFIER(__set__); stack[0] = target; if (value == NULL) { @@ -6661,7 +6666,6 @@ slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value) static int slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds) { - _Py_IDENTIFIER(__init__); int unbound; PyObject *meth = lookup_method(self, &PyId___init__, &unbound); PyObject *res; @@ -6706,7 +6710,6 @@ slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) static void slot_tp_finalize(PyObject *self) { - _Py_IDENTIFIER(__del__); int unbound; PyObject *del, *res; PyObject *error_type, *error_value, *error_traceback; @@ -6734,7 +6737,6 @@ slot_am_await(PyObject *self) { int unbound; PyObject *func, *res; - _Py_IDENTIFIER(__await__); func = lookup_maybe_method(self, &PyId___await__, &unbound); if (func != NULL) { @@ -6753,7 +6755,6 @@ slot_am_aiter(PyObject *self) { int unbound; PyObject *func, *res; - _Py_IDENTIFIER(__aiter__); func = lookup_maybe_method(self, &PyId___aiter__, &unbound); if (func != NULL) { @@ -6772,7 +6773,6 @@ slot_am_anext(PyObject *self) { int unbound; PyObject *func, *res; - _Py_IDENTIFIER(__anext__); func = lookup_maybe_method(self, &PyId___anext__, &unbound); if (func != NULL) { @@ -7078,6 +7078,10 @@ slotptr(PyTypeObject *type, int ioffset) appropriate to declare fixed-size arrays for this. */ #define MAX_EQUIV 10 +/* These act as a little cache. */ +static PyObject *last_slot_name = NULL; +static slotdef *last_slot_ptrs[MAX_EQUIV]; + /* Return a slot pointer for a given name, but ONLY if the attribute has exactly one slot function. The name must be an interned string. */ static void ** @@ -7085,16 +7089,14 @@ resolve_slotdups(PyTypeObject *type, PyObject *name) { /* XXX Maybe this could be optimized more -- but is it worth it? */ - /* pname and ptrs act as a little cache */ - static PyObject *pname; - static slotdef *ptrs[MAX_EQUIV]; slotdef *p, **pp; void **res, **ptr; + slotdef **ptrs = last_slot_ptrs; - if (pname != name) { + if (last_slot_name != name) { /* Collect all slotdefs that match name into ptrs. */ - pname = name; - pp = ptrs; + last_slot_name = name; + pp = last_slot_ptrs; for (p = slotdefs; p->name_strobj; p++) { if (p->name_strobj == name) *pp++ = p; diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index eaba5836cb1c71..abc9f55ca6bbef 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -195,6 +195,8 @@ extern "C" { # define OVERALLOCATE_FACTOR 4 #endif +_Py_IDENTIFIER(iter); + /* This dictionary holds all interned unicode strings. Note that references to strings in this dictionary are *not* counted in the string's ob_refcnt. When the interned string reaches a refcnt of 0 the string deallocation @@ -4158,7 +4160,8 @@ unicode_decode_call_errorhandler_wchar( Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr, wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos) { - static const char *argparse = "Un;decoding error handler must return (str, int) tuple"; + static const char *argparse = // Static is okay here (immutable data). + "Un;decoding error handler must return (str, int) tuple"; PyObject *restuple = NULL; PyObject *repunicode = NULL; @@ -4262,7 +4265,8 @@ unicode_decode_call_errorhandler_writer( Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr, _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */) { - static const char *argparse = "Un;decoding error handler must return (str, int) tuple"; + static const char *argparse = // Static is okay here (immutable data). + "Un;decoding error handler must return (str, int) tuple"; PyObject *restuple = NULL; PyObject *repunicode = NULL; @@ -6705,7 +6709,8 @@ unicode_encode_call_errorhandler(const char *errors, Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos) { - static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple"; + static const char *argparse = // Static is okay here (immutable data). + "On;encoding error handler must return (str/bytes, int) tuple"; Py_ssize_t len; PyObject *restuple; PyObject *resunicode; @@ -8694,7 +8699,8 @@ unicode_translate_call_errorhandler(const char *errors, Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos) { - static const char *argparse = "Un;translating error handler must return (str, int) tuple"; + static const char *argparse = // Static is okay here (immutable data). + "Un;translating error handler must return (str, int) tuple"; Py_ssize_t i_newpos; PyObject *restuple; @@ -15439,7 +15445,6 @@ PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list( static PyObject * unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored)) { - _Py_IDENTIFIER(iter); if (it->it_seq != NULL) { return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter), it->it_seq, it->it_index); diff --git a/Objects/weakrefobject.c b/Objects/weakrefobject.c index ff6d92254f7fe2..eebb663d49bbd9 100644 --- a/Objects/weakrefobject.c +++ b/Objects/weakrefobject.c @@ -6,6 +6,9 @@ ((PyWeakReference **) PyObject_GET_WEAKREFS_LISTPTR(o)) +_Py_IDENTIFIER(__name__); + + Py_ssize_t _PyWeakref_GetWeakrefCount(PyWeakReference *head) { @@ -158,7 +161,6 @@ static PyObject * weakref_repr(PyWeakReference *self) { PyObject *name, *repr; - _Py_IDENTIFIER(__name__); if (PyWeakref_GET_OBJECT(self) == Py_None) return PyUnicode_FromFormat("", self); diff --git a/Parser/grammar1.c b/Parser/grammar1.c index e0b8fbb8b82886..3c57e35f8f0be2 100644 --- a/Parser/grammar1.c +++ b/Parser/grammar1.c @@ -19,7 +19,7 @@ PyGrammar_FindDFA(grammar *g, int type) const char * PyGrammar_LabelRepr(label *lb) { - static char buf[100]; + static char buf[100]; // Static is okay here (buffer, non-threaded). if (lb->lb_type == ENDMARKER) return "EMPTY"; diff --git a/Parser/myreadline.c b/Parser/myreadline.c index 43e5583b8bcc43..e16d7be2b6448a 100644 --- a/Parser/myreadline.c +++ b/Parser/myreadline.c @@ -101,7 +101,7 @@ extern char _get_console_type(HANDLE handle); char * _PyOS_WindowsConsoleReadline(HANDLE hStdIn) { - static wchar_t wbuf_local[1024 * 16]; + static wchar_t wbuf_local[1024 * 16]; // Static is okay here (buffer, non-threaded). const DWORD chunk_size = 1024; DWORD n_read, total_read, wbuflen, u8len; diff --git a/Parser/tokenizer.c b/Parser/tokenizer.c index 5dc2ae65c42daf..9e9c77494d1c86 100644 --- a/Parser/tokenizer.c +++ b/Parser/tokenizer.c @@ -31,6 +31,9 @@ || c == '_'\ || (c >= 128)) +_Py_IDENTIFIER(open); +_Py_IDENTIFIER(readline); + extern char *PyOS_Readline(FILE *, FILE *, const char *); /* Return malloc'ed string including trailing \n; empty malloc'ed string for EOF; @@ -412,8 +415,6 @@ static int fp_setreadl(struct tok_state *tok, const char* enc) { PyObject *readline, *io, *stream; - _Py_IDENTIFIER(open); - _Py_IDENTIFIER(readline); int fd; long pos; diff --git a/Python/Python-ast.c b/Python/Python-ast.c index cb53a41cdf35bd..195c558f76f48b 100644 --- a/Python/Python-ast.c +++ b/Python/Python-ast.c @@ -5,6 +5,10 @@ #include "Python.h" #include "Python-ast.h" +_Py_IDENTIFIER(__dict__); +_Py_IDENTIFIER(__module__); +_Py_IDENTIFIER(_ast); + static PyTypeObject AST_type; static PyTypeObject *mod_type; static PyObject* ast2obj_mod(void*); @@ -613,7 +617,6 @@ ast_type_init(PyObject *self, PyObject *args, PyObject *kw) static PyObject * ast_type_reduce(PyObject *self, PyObject *unused) { - _Py_IDENTIFIER(__dict__); PyObject *dict; if (_PyObject_LookupAttrId(self, &PyId___dict__, &dict) < 0) { return NULL; @@ -679,8 +682,6 @@ static PyTypeObject AST_type = { static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields) { - _Py_IDENTIFIER(__module__); - _Py_IDENTIFIER(_ast); PyObject *fnames, *result; int i; fnames = PyTuple_New(num_fields); @@ -838,9 +839,10 @@ static int add_ast_fields(void) } +static int initialized; + static int init_types(void) { - static int initialized; if (initialized) return 1; if (add_ast_fields() < 0) return 0; mod_type = make_type("mod", &AST_type, NULL, 0); diff --git a/Python/_warnings.c b/Python/_warnings.c index 0b192580e1073e..af3765b33a8228 100644 --- a/Python/_warnings.c +++ b/Python/_warnings.c @@ -9,7 +9,20 @@ PyDoc_STRVAR(warnings__doc__, MODULE_NAME " provides basic warning filtering support.\n" "It is a helper module to speed up interpreter start-up."); +_Py_IDENTIFIER(__loader__); +_Py_IDENTIFIER(__name__); +_Py_IDENTIFIER(__warningregistry__); +_Py_IDENTIFIER(_showwarnmsg); +_Py_IDENTIFIER(_warn_unawaited_coroutine); +_Py_IDENTIFIER(defaultaction); +_Py_IDENTIFIER(filters); +_Py_IDENTIFIER(get_source); +_Py_IDENTIFIER(match); +_Py_IDENTIFIER(onceregistry); _Py_IDENTIFIER(stderr); +_Py_IDENTIFIER(version); +_Py_IDENTIFIER(warnings); +_Py_IDENTIFIER(WarningMessage); #ifndef Py_DEBUG _Py_IDENTIFIER(default); _Py_IDENTIFIER(ignore); @@ -147,7 +160,6 @@ static int check_matched(PyObject *obj, PyObject *arg) { PyObject *result; - _Py_IDENTIFIER(match); int rc; /* A 'None' filter always matches */ @@ -182,7 +194,6 @@ get_warnings_attr(_Py_Identifier *attr_id, int try_import) { PyObject *warnings_str; PyObject *warnings_module, *obj; - _Py_IDENTIFIER(warnings); warnings_str = _PyUnicode_FromId(&PyId_warnings); if (warnings_str == NULL) { @@ -224,7 +235,6 @@ static PyObject * get_once_registry(WarningsState *st) { PyObject *registry; - _Py_IDENTIFIER(onceregistry); registry = get_warnings_attr(&PyId_onceregistry, 0); if (registry == NULL) { @@ -250,7 +260,6 @@ static PyObject * get_default_action(WarningsState *st) { PyObject *default_action; - _Py_IDENTIFIER(defaultaction); default_action = get_warnings_attr(&PyId_defaultaction, 0); if (default_action == NULL) { @@ -281,7 +290,6 @@ get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno, PyObject *action; Py_ssize_t i; PyObject *warnings_filters; - _Py_IDENTIFIER(filters); WarningsState *st = _Warnings_GetState(); if (st == NULL) { return NULL; @@ -379,7 +387,6 @@ static int already_warned(PyObject *registry, PyObject *key, int should_set) { PyObject *version_obj, *already_warned; - _Py_IDENTIFIER(version); if (key == NULL) return -1; @@ -482,7 +489,6 @@ show_warning(PyObject *filename, int lineno, PyObject *text, PyObject *f_stderr; PyObject *name; char lineno_str[128]; - _Py_IDENTIFIER(__name__); PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno); @@ -554,8 +560,6 @@ call_show_warning(PyObject *category, PyObject *text, PyObject *message, PyObject *sourceline, PyObject *source) { PyObject *show_fn, *msg, *res, *warnmsg_cls = NULL; - _Py_IDENTIFIER(_showwarnmsg); - _Py_IDENTIFIER(WarningMessage); /* If the source parameter is set, try to get the Python implementation. The Python implementation is able to log the traceback where the source @@ -751,11 +755,12 @@ warn_explicit(PyObject *category, PyObject *message, return result; /* Py_None or NULL. */ } +static PyObject *importlib_string = NULL; +static PyObject *bootstrap_string = NULL; + static int is_internal_frame(PyFrameObject *frame) { - static PyObject *importlib_string = NULL; - static PyObject *bootstrap_string = NULL; PyObject *filename; int contains; @@ -815,8 +820,6 @@ static int setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno, PyObject **module, PyObject **registry) { - _Py_IDENTIFIER(__warningregistry__); - _Py_IDENTIFIER(__name__); PyObject *globals; /* Setup globals, filename and lineno. */ @@ -965,9 +968,6 @@ warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category, static PyObject * get_source_line(PyObject *module_globals, int lineno) { - _Py_IDENTIFIER(get_source); - _Py_IDENTIFIER(__loader__); - _Py_IDENTIFIER(__name__); PyObject *loader; PyObject *module_name; PyObject *get_source; @@ -1024,9 +1024,9 @@ get_source_line(PyObject *module_globals, int lineno) static PyObject * warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwd_list[] = {"message", "category", "filename", "lineno", - "module", "registry", "module_globals", - "source", 0}; + static char *kwlist[] = {"message", "category", "filename", "lineno", + "module", "registry", "module_globals", + "source", 0}; PyObject *message; PyObject *category; PyObject *filename; @@ -1039,7 +1039,7 @@ warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds) PyObject *returned; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOOO:warn_explicit", - kwd_list, &message, &category, &filename, &lineno, &module, + kwlist, &message, &category, &filename, &lineno, &module, ®istry, &module_globals, &sourceobj)) return NULL; @@ -1279,7 +1279,6 @@ _PyErr_WarnUnawaitedCoroutine(PyObject *coro) Since this is called from __del__ context, it's careful to never raise an exception. */ - _Py_IDENTIFIER(_warn_unawaited_coroutine); int warned = 0; PyObject *fn = get_warnings_attr(&PyId__warn_unawaited_coroutine, 1); if (fn) { diff --git a/Python/ast.c b/Python/ast.c index 03da4e7f7f9aff..0b348c98cf17f6 100644 --- a/Python/ast.c +++ b/Python/ast.c @@ -15,6 +15,8 @@ #define MAXLEVEL 200 /* Max parentheses level */ +_Py_IDENTIFIER(NFKC); + static int validate_stmts(asdl_seq *); static int validate_exprs(asdl_seq *, expr_context_ty, int); static int validate_nonempty_seq(asdl_seq *, const char *, const char *); @@ -618,7 +620,6 @@ new_identifier(const char *n, struct compiling *c) identifier; if so, normalize to NFKC. */ if (!PyUnicode_IS_ASCII(id)) { PyObject *id2; - _Py_IDENTIFIER(NFKC); if (!c->c_normalize && !init_normalization(c)) { Py_DECREF(id); return NULL; @@ -3178,7 +3179,7 @@ ast_for_call(struct compiling *c, const node *n, expr_ty func, // To remain LL(1), the grammar accepts any test (basically, any // expression) in the keyword slot of a call site. So, we need // to manually enforce that the keyword is a NAME here. - static const int name_tree[] = { + static const int name_tree[] = { // Static is okay here (immutable data). test, or_test, and_test, diff --git a/Python/ast_opt.c b/Python/ast_opt.c index 96c766fc0957d4..c5763adb7bc554 100644 --- a/Python/ast_opt.c +++ b/Python/ast_opt.c @@ -75,7 +75,7 @@ fold_unaryop(expr_ty node, PyArena *arena, int optimize) } typedef PyObject *(*unary_op)(PyObject*); - static const unary_op ops[] = { + static const unary_op ops[] = { // Static is okay here (immutable data). [Invert] = PyNumber_Invert, [Not] = unary_not, [UAdd] = PyNumber_Positive, diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 047cca057b41ae..6295e26ed940ca 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -1851,8 +1851,8 @@ builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z) static PyObject * builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { - static const char * const _keywords[] = {"sep", "end", "file", "flush", 0}; - static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0}; + static const char * const _kwlist[] = {"sep", "end", "file", "flush", 0}; + static struct _PyArg_Parser _parser = {"|OOOO:print", _kwlist, 0}; // Static is okay here (immutable data). PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL; int i, err; diff --git a/Python/bootstrap_hash.c b/Python/bootstrap_hash.c index dd752b86094d4b..6630f5407f9aaf 100644 --- a/Python/bootstrap_hash.c +++ b/Python/bootstrap_hash.c @@ -102,7 +102,7 @@ py_getrandom(void *buffer, Py_ssize_t size, int blocking, int raise) /* Is getrandom() supported by the running kernel? Set to 0 if getrandom() failed with ENOSYS or EPERM. Need Linux kernel 3.17 or newer, or Solaris 11.3 or newer */ - static int getrandom_works = 1; + static int getrandom_works = 1; // Static is okay here (process-global). int flags; char *dest; long n; @@ -212,7 +212,7 @@ py_getentropy(char *buffer, Py_ssize_t size, int raise) { /* Is getentropy() supported by the running kernel? Set to 0 if getentropy() failed with ENOSYS or EPERM. */ - static int getentropy_works = 1; + static int getentropy_works = 1; // Static is okay here (process-global). if (!getentropy_works) { return 0; diff --git a/Python/ceval.c b/Python/ceval.c index 1bb4704572b44b..5d7a0124a56dfb 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -35,6 +35,22 @@ # error "ceval.c must be build with Py_BUILD_CORE define for best performance" #endif +_Py_IDENTIFIER(__aenter__); +_Py_IDENTIFIER(__aexit__); +_Py_IDENTIFIER(__all__); +_Py_IDENTIFIER(__annotations__); +_Py_IDENTIFIER(__build_class__); +_Py_IDENTIFIER(__dict__); +_Py_IDENTIFIER(__enter__); +_Py_IDENTIFIER(__exit__); +_Py_IDENTIFIER(__import__); +#ifdef LLTRACE +_Py_IDENTIFIER(__ltrace__); +#endif +_Py_IDENTIFIER(__name__); +_Py_IDENTIFIER(displayhook); +_Py_IDENTIFIER(send); + /* Private API for the LOAD_METHOD opcode. */ extern int _PyObject_GetMethod(PyObject *, PyObject *, PyObject **); @@ -479,21 +495,21 @@ handle_signals(_PyRuntimeState *runtime) return 0; } +static int pending_calls_busy = 0; + static int make_pending_calls(_PyRuntimeState *runtime) { - static int busy = 0; - /* only service pending calls on main thread */ if (PyThread_get_thread_ident() != runtime->main_thread) { return 0; } /* don't perform recursive pending calls */ - if (busy) { + if (pending_calls_busy) { return 0; } - busy = 1; + pending_calls_busy = 1; struct _ceval_runtime_state *ceval = &runtime->ceval; /* unsignal before starting to call callbacks, so that any callback added in-between re-signals */ @@ -521,11 +537,11 @@ make_pending_calls(_PyRuntimeState *runtime) } } - busy = 0; + pending_calls_busy = 0; return res; error: - busy = 0; + pending_calls_busy = 0; SIGNAL_PENDING_CALLS(ceval); return res; } @@ -716,10 +732,6 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag) PyObject *names; PyObject *consts; -#ifdef LLTRACE - _Py_IDENTIFIER(__ltrace__); -#endif - /* Computed GOTOs, or the-optimization-commonly-but-improperly-known-as-"threaded code" using gcc's labels-as-values extension @@ -1757,7 +1769,6 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag) } case TARGET(PRINT_EXPR): { - _Py_IDENTIFIER(displayhook); PyObject *value = POP(); PyObject *hook = _PySys_GetObjectId(&PyId_displayhook); PyObject *res; @@ -1945,7 +1956,6 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag) if (PyGen_CheckExact(receiver) || PyCoro_CheckExact(receiver)) { retval = _PyGen_Send((PyGenObject *)receiver, v); } else { - _Py_IDENTIFIER(send); if (v == Py_None) retval = Py_TYPE(receiver)->tp_iternext(receiver); else @@ -2140,7 +2150,6 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag) } case TARGET(LOAD_BUILD_CLASS): { - _Py_IDENTIFIER(__build_class__); PyObject *bc; if (PyDict_CheckExact(f->f_builtins)) { @@ -2656,7 +2665,6 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag) } case TARGET(SETUP_ANNOTATIONS): { - _Py_IDENTIFIER(__annotations__); int err; PyObject *ann_dict; if (f->f_locals == NULL) { @@ -3083,8 +3091,6 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag) } case TARGET(BEFORE_ASYNC_WITH): { - _Py_IDENTIFIER(__aexit__); - _Py_IDENTIFIER(__aenter__); PyObject *mgr = TOP(); PyObject *exit = special_lookup(mgr, &PyId___aexit__), @@ -3117,8 +3123,6 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag) } case TARGET(SETUP_WITH): { - _Py_IDENTIFIER(__exit__); - _Py_IDENTIFIER(__enter__); PyObject *mgr = TOP(); PyObject *enter = special_lookup(mgr, &PyId___enter__), *exit; PyObject *res; @@ -5012,7 +5016,6 @@ cmp_outcome(int op, PyObject *v, PyObject *w) static PyObject * import_name(PyFrameObject *f, PyObject *name, PyObject *fromlist, PyObject *level) { - _Py_IDENTIFIER(__import__); PyObject *import_func, *res; PyObject* stack[5]; @@ -5055,7 +5058,6 @@ static PyObject * import_from(PyObject *v, PyObject *name) { PyObject *x; - _Py_IDENTIFIER(__name__); PyObject *fullmodname, *pkgname, *pkgpath, *pkgname_or_unknown, *errmsg; if (_PyObject_LookupAttr(v, name, &x) != 0) { @@ -5123,9 +5125,6 @@ import_from(PyObject *v, PyObject *name) static int import_all_from(PyObject *locals, PyObject *v) { - _Py_IDENTIFIER(__all__); - _Py_IDENTIFIER(__dict__); - _Py_IDENTIFIER(__name__); PyObject *all, *dict, *name, *value; int skip_leading_underscores = 0; int pos, err; diff --git a/Python/codecs.c b/Python/codecs.c index d4b34f8397f05a..ce50f715973751 100644 --- a/Python/codecs.c +++ b/Python/codecs.c @@ -13,6 +13,9 @@ Copyright (c) Corporation for National Research Initiatives. #include "ucnhash.h" #include + +_Py_IDENTIFIER(_is_text_encoding); + const char *Py_hexdigits = "0123456789abcdef"; /* --- Codec Registry ----------------------------------------------------- */ @@ -528,7 +531,6 @@ PyObject *PyCodec_Decode(PyObject *object, PyObject * _PyCodec_LookupTextEncoding(const char *encoding, const char *alternate_command) { - _Py_IDENTIFIER(_is_text_encoding); PyObject *codec; PyObject *attr; int is_text_codec; @@ -1414,7 +1416,7 @@ static PyObject *surrogateescape_errors(PyObject *self, PyObject *exc) static int _PyCodecRegistry_Init(void) { - static struct { + static struct { // Static is okay here (immutable data). char *name; PyMethodDef def; } methods[] = diff --git a/Python/compile.c b/Python/compile.c index 91ce04b02e53c9..baad6991f110cc 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -31,6 +31,9 @@ #include "opcode.h" #include "wordcode_helpers.h" + +_Py_IDENTIFIER(__class__); + #define DEFAULT_BLOCK_SIZE 16 #define DEFAULT_BLOCKS 8 #define DEFAULT_CODE_SIZE 128 @@ -572,7 +575,6 @@ compiler_enter_scope(struct compiler *c, identifier name, } if (u->u_ste->ste_needs_class_closure) { /* Cook up an implicit __class__ cell. */ - _Py_IDENTIFIER(__class__); PyObject *name; int res; assert(u->u_scope_type == COMPILER_SCOPE_CLASS); @@ -1717,19 +1719,20 @@ compiler_body(struct compiler *c, asdl_seq *stmts) return 1; } +static PyObject *cached_name_module = NULL; + static PyCodeObject * compiler_mod(struct compiler *c, mod_ty mod) { PyCodeObject *co; int addNone = 1; - static PyObject *module; - if (!module) { - module = PyUnicode_InternFromString(""); - if (!module) + if (!cached_name_module) { + cached_name_module = PyUnicode_InternFromString(""); + if (!cached_name_module) return NULL; } /* Use 0 for firstlineno initially, will fixup in assemble(). */ - if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0)) + if (!compiler_enter_scope(c, cached_name_module, COMPILER_SCOPE_MODULE, mod, 0)) return NULL; switch (mod->kind) { case Module_kind: @@ -1973,6 +1976,8 @@ compiler_visit_argannotations(struct compiler *c, asdl_seq* args, return 1; } +static identifier return_str = NULL; + static int compiler_visit_annotations(struct compiler *c, arguments_ty args, expr_ty returns) @@ -1982,7 +1987,6 @@ compiler_visit_annotations(struct compiler *c, arguments_ty args, Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed. */ - static identifier return_str; PyObject *names; Py_ssize_t len; names = PyList_New(0); @@ -2481,19 +2485,20 @@ compiler_ifexp(struct compiler *c, expr_ty e) return 1; } +static identifier cached_name_lambda; + static int compiler_lambda(struct compiler *c, expr_ty e) { PyCodeObject *co; PyObject *qualname; - static identifier name; Py_ssize_t funcflags; arguments_ty args = e->v.Lambda.args; assert(e->kind == Lambda_kind); - if (!name) { - name = PyUnicode_InternFromString(""); - if (!name) + if (!cached_name_lambda) { + cached_name_lambda = PyUnicode_InternFromString(""); + if (!cached_name_lambda) return 0; } @@ -2502,7 +2507,7 @@ compiler_lambda(struct compiler *c, expr_ty e) return 0; } - if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA, + if (!compiler_enter_scope(c, cached_name_lambda, COMPILER_SCOPE_LAMBDA, (void *)e, e->lineno)) return 0; @@ -3082,12 +3087,13 @@ compiler_import(struct compiler *c, stmt_ty s) return 1; } +static PyObject *empty_string; + static int compiler_from_import(struct compiler *c, stmt_ty s) { Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names); PyObject *names; - static PyObject *empty_string; if (!empty_string) { empty_string = PyUnicode_FromString(""); @@ -3146,17 +3152,18 @@ compiler_from_import(struct compiler *c, stmt_ty s) return 1; } +static PyObject *cached_name_assertion_error = NULL; + static int compiler_assert(struct compiler *c, stmt_ty s) { - static PyObject *assertion_error = NULL; basicblock *end; if (c->c_optimize) return 1; - if (assertion_error == NULL) { - assertion_error = PyUnicode_InternFromString("AssertionError"); - if (assertion_error == NULL) + if (cached_name_assertion_error == NULL) { + cached_name_assertion_error = PyUnicode_InternFromString("AssertionError"); + if (cached_name_assertion_error == NULL) return 0; } if (s->v.Assert.test->kind == Tuple_kind && @@ -3173,7 +3180,7 @@ compiler_assert(struct compiler *c, stmt_ty s) return 0; if (!compiler_jump_if(c, s->v.Assert.test, end, 1)) return 0; - ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); + ADDOP_O(c, LOAD_GLOBAL, cached_name_assertion_error, names); if (s->v.Assert.msg) { VISIT(c, expr, s->v.Assert.msg); ADDOP_I(c, CALL_FUNCTION, 1); @@ -4449,63 +4456,67 @@ compiler_comprehension(struct compiler *c, expr_ty e, int type, return 0; } +static identifier cached_name_getexpr; + static int compiler_genexp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_InternFromString(""); - if (!name) + if (!cached_name_getexpr) { + cached_name_getexpr = PyUnicode_InternFromString(""); + if (!cached_name_getexpr) return 0; } assert(e->kind == GeneratorExp_kind); - return compiler_comprehension(c, e, COMP_GENEXP, name, + return compiler_comprehension(c, e, COMP_GENEXP, cached_name_getexpr, e->v.GeneratorExp.generators, e->v.GeneratorExp.elt, NULL); } +static identifier cached_name_listcomp; + static int compiler_listcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_InternFromString(""); - if (!name) + if (!cached_name_listcomp) { + cached_name_listcomp = PyUnicode_InternFromString(""); + if (!cached_name_listcomp) return 0; } assert(e->kind == ListComp_kind); - return compiler_comprehension(c, e, COMP_LISTCOMP, name, + return compiler_comprehension(c, e, COMP_LISTCOMP, cached_name_listcomp, e->v.ListComp.generators, e->v.ListComp.elt, NULL); } +static identifier cached_name_setcomp; + static int compiler_setcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_InternFromString(""); - if (!name) + if (!cached_name_setcomp) { + cached_name_setcomp = PyUnicode_InternFromString(""); + if (!cached_name_setcomp) return 0; } assert(e->kind == SetComp_kind); - return compiler_comprehension(c, e, COMP_SETCOMP, name, + return compiler_comprehension(c, e, COMP_SETCOMP, cached_name_setcomp, e->v.SetComp.generators, e->v.SetComp.elt, NULL); } +static identifier cached_name_dictcomp; + static int compiler_dictcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_InternFromString(""); - if (!name) + if (!cached_name_dictcomp) { + cached_name_dictcomp = PyUnicode_InternFromString(""); + if (!cached_name_dictcomp) return 0; } assert(e->kind == DictComp_kind); - return compiler_comprehension(c, e, COMP_DICTCOMP, name, + return compiler_comprehension(c, e, COMP_DICTCOMP, cached_name_dictcomp, e->v.DictComp.generators, e->v.DictComp.key, e->v.DictComp.value); } diff --git a/Python/dtoa.c b/Python/dtoa.c index b7bb7acfb6c215..c8810fccad45ad 100644 --- a/Python/dtoa.c +++ b/Python/dtoa.c @@ -686,7 +686,7 @@ pow5mult(Bigint *b, int k) { Bigint *b1, *p5, *p51; int i; - static const int p05[3] = { 5, 25, 125 }; + static const int p05[3] = { 5, 25, 125 }; // Static is okay here (immutable data). if ((i = k & 3)) { b = multadd(b, p05[i-1], 0); @@ -742,7 +742,7 @@ pow5mult(Bigint *b, int k) { Bigint *b1, *p5, *p51; int i; - static const int p05[3] = { 5, 25, 125 }; + static const int p05[3] = { 5, 25, 125 }; // Static is okay here (immutable data). if ((i = k & 3)) { b = multadd(b, p05[i-1], 0); diff --git a/Python/dynamic_annotations.c b/Python/dynamic_annotations.c index 7febaa09df1950..349f95b2703ad0 100644 --- a/Python/dynamic_annotations.c +++ b/Python/dynamic_annotations.c @@ -142,7 +142,7 @@ static int GetRunningOnValgrind(void) { /* See the comments in dynamic_annotations.h */ int RunningOnValgrind(void) { - static volatile int running_on_valgrind = -1; + static volatile int running_on_valgrind = -1; // Static is okay here (process-global). /* C doesn't have thread-safe initialization of statics, and we don't want to depend on pthread_once here, so hack it. */ int local_running_on_valgrind = running_on_valgrind; diff --git a/Python/dynload_aix.c b/Python/dynload_aix.c index b3ff8e288c1a6a..d17194f8897883 100644 --- a/Python/dynload_aix.c +++ b/Python/dynload_aix.c @@ -154,6 +154,8 @@ aix_loaderror(const char *pathname) } +static void *staticmodlistptr = NULL; + dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix, const char *shortname, const char *pathname, FILE *fp) @@ -169,8 +171,6 @@ dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix, -- with loadquery(L_GETINFO). */ - static void *staticmodlistptr = NULL; - if (!staticmodlistptr) if (aix_getoldmodules(&staticmodlistptr) == -1) return NULL; diff --git a/Python/errors.c b/Python/errors.c index b8af1df4161d57..4fa85b8f8780f5 100644 --- a/Python/errors.c +++ b/Python/errors.c @@ -21,8 +21,15 @@ extern char *strerror(int); extern "C" { #endif +_Py_IDENTIFIER(__module__); _Py_IDENTIFIER(builtins); +_Py_IDENTIFIER(filename); +_Py_IDENTIFIER(lineno); +_Py_IDENTIFIER(msg); +_Py_IDENTIFIER(offset); +_Py_IDENTIFIER(print_file_and_line); _Py_IDENTIFIER(stderr); +_Py_IDENTIFIER(text); void @@ -858,7 +865,6 @@ PyErr_Format(PyObject *exception, const char *format, ...) PyObject * PyErr_NewException(const char *name, PyObject *base, PyObject *dict) { - _Py_IDENTIFIER(__module__); const char *dot; PyObject *modulename = NULL; PyObject *classname = NULL; @@ -949,7 +955,6 @@ PyErr_NewExceptionWithDoc(const char *name, const char *doc, void PyErr_WriteUnraisable(PyObject *obj) { - _Py_IDENTIFIER(__module__); PyObject *f, *t, *v, *tb; PyObject *moduleName = NULL; const char *className; @@ -1049,12 +1054,6 @@ void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) { PyObject *exc, *v, *tb, *tmp; - _Py_IDENTIFIER(filename); - _Py_IDENTIFIER(lineno); - _Py_IDENTIFIER(msg); - _Py_IDENTIFIER(offset); - _Py_IDENTIFIER(print_file_and_line); - _Py_IDENTIFIER(text); /* add attributes for the line number and filename for the error */ PyErr_Fetch(&exc, &v, &tb); diff --git a/Python/fileutils.c b/Python/fileutils.c index dfad48edb81a1d..71087964f2e144 100644 --- a/Python/fileutils.c +++ b/Python/fileutils.c @@ -1091,7 +1091,7 @@ set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works) DWORD flags; #else #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX) - static int ioctl_works = -1; + static int ioctl_works = -1; // Static is okay here (process-global). int request; int err; #endif diff --git a/Python/getversion.c b/Python/getversion.c index c32b6f9d60d4b7..8d4720ccef90a1 100644 --- a/Python/getversion.c +++ b/Python/getversion.c @@ -8,7 +8,7 @@ const char * Py_GetVersion(void) { - static char version[250]; + static char version[250]; // Static is okay here (buffer, non-threaded?). PyOS_snprintf(version, sizeof(version), "%.80s (%.80s) %.80s", PY_VERSION, Py_GetBuildInfo(), Py_GetCompiler()); return version; diff --git a/Python/import.c b/Python/import.c index c634edb4c7fcb7..7571a6db63b55a 100644 --- a/Python/import.c +++ b/Python/import.c @@ -25,6 +25,24 @@ extern "C" { #define CACHEDIR "__pycache__" + +_Py_IDENTIFIER(__builtins__); +_Py_IDENTIFIER(__name__); +_Py_IDENTIFIER(__package__); +_Py_IDENTIFIER(__path__); +_Py_IDENTIFIER(__spec__); +_Py_IDENTIFIER(_find_and_load); +_Py_IDENTIFIER(_fix_up_module); +_Py_IDENTIFIER(_get_sourcefile); +_Py_IDENTIFIER(_handle_fromlist); +_Py_IDENTIFIER(_lock_unlock_module); +_Py_IDENTIFIER(clear); +_Py_IDENTIFIER(imp); +_Py_IDENTIFIER(parent); +_Py_IDENTIFIER(reload); +_Py_IDENTIFIER(zipimporter); + + /* See _PyImport_FixupExtensionObject() below */ static PyObject *extensions = NULL; @@ -115,7 +133,6 @@ _PyImportZip_Init(PyInterpreterState *interp) } } else { - _Py_IDENTIFIER(zipimporter); PyObject *zipimporter = _PyObject_GetAttrId(zipimport, &PyId_zipimporter); Py_DECREF(zipimport); @@ -521,7 +538,6 @@ PyImport_Cleanup(void) PyDict_Clear(modules); } else { - _Py_IDENTIFIER(clear); if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) { PyErr_WriteUnraisable(NULL); } @@ -916,7 +932,6 @@ PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, } else if (cpathobj != NULL) { PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE(); - _Py_IDENTIFIER(_get_sourcefile); if (interp == NULL) { Py_FatalError("PyImport_ExecCodeModuleWithPathnames: " @@ -948,7 +963,6 @@ PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, static PyObject * module_dict_for_exec(PyObject *name) { - _Py_IDENTIFIER(__builtins__); PyObject *m, *d = NULL; m = PyImport_AddModuleObject(name); @@ -998,7 +1012,6 @@ PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, { PyObject *d, *external, *res; PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE(); - _Py_IDENTIFIER(_fix_up_module); d = module_dict_for_exec(name); if (d == NULL) { @@ -1501,11 +1514,6 @@ remove_importlib_frames(PyInterpreterState *interp) static PyObject * resolve_name(PyObject *name, PyObject *globals, int level) { - _Py_IDENTIFIER(__spec__); - _Py_IDENTIFIER(__package__); - _Py_IDENTIFIER(__path__); - _Py_IDENTIFIER(__name__); - _Py_IDENTIFIER(parent); PyObject *abs_name; PyObject *package = NULL; PyObject *spec; @@ -1649,15 +1657,16 @@ resolve_name(PyObject *name, PyObject *globals, int level) return NULL; } +static int import_level = 0; +static _PyTime_t accumulated = 0; +static int header = 1; + static PyObject * import_find_and_load(PyObject *abs_name) { - _Py_IDENTIFIER(_find_and_load); PyObject *mod = NULL; PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE(); int import_time = interp->core_config.import_time; - static int import_level; - static _PyTime_t accumulated; _PyTime_t t1 = 0, accumulated_copy = accumulated; @@ -1667,7 +1676,6 @@ import_find_and_load(PyObject *abs_name) * _PyDict_GetItemIdWithError(). */ if (import_time) { - static int header = 1; if (header) { fputs("import time: self [us] | cumulative | imported package\n", stderr); @@ -1710,7 +1718,6 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) { - _Py_IDENTIFIER(_handle_fromlist); PyObject *abs_name = NULL; PyObject *final_mod = NULL; PyObject *mod = NULL; @@ -1758,8 +1765,6 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, } if (mod != NULL && mod != Py_None) { - _Py_IDENTIFIER(__spec__); - _Py_IDENTIFIER(_lock_unlock_module); PyObject *spec; /* Optimization: only call _bootstrap._lock_unlock_module() if @@ -1847,7 +1852,6 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, } } else { - _Py_IDENTIFIER(__path__); PyObject *path; if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) { goto error; @@ -1895,8 +1899,6 @@ PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals PyObject * PyImport_ReloadModule(PyObject *m) { - _Py_IDENTIFIER(imp); - _Py_IDENTIFIER(reload); PyObject *reloaded_module = NULL; PyObject *imp = _PyImport_GetModuleId(&PyId_imp); if (imp == NULL) { @@ -1925,12 +1927,13 @@ PyImport_ReloadModule(PyObject *m) e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache")) will return instead of . */ +static PyObject *silly_list = NULL; +static PyObject *builtins_str = NULL; +static PyObject *import_str = NULL; + PyObject * PyImport_Import(PyObject *module_name) { - static PyObject *silly_list = NULL; - static PyObject *builtins_str = NULL; - static PyObject *import_str = NULL; PyObject *globals = NULL; PyObject *import = NULL; PyObject *builtins = NULL; diff --git a/Python/importdl.c b/Python/importdl.c index 50231ff28848a1..fae2de61305812 100644 --- a/Python/importdl.c +++ b/Python/importdl.c @@ -23,6 +23,8 @@ extern dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix, const char *pathname, FILE *fp); #endif +_Py_IDENTIFIER(replace); + static const char * const ascii_only_prefix = "PyInit"; static const char * const nonascii_prefix = "PyInitU"; @@ -38,7 +40,6 @@ get_encoded_name(PyObject *name, const char **hook_prefix) { PyObject *encoded = NULL; PyObject *modname = NULL; Py_ssize_t name_len, lastdot; - _Py_IDENTIFIER(replace); /* Get the short name (substring after last dot) */ name_len = PyUnicode_GetLength(name); diff --git a/Python/marshal.c b/Python/marshal.c index caaddfe9e44e49..f8c5e8a3fa00c6 100644 --- a/Python/marshal.c +++ b/Python/marshal.c @@ -14,6 +14,11 @@ #include "marshal.h" #include "../Modules/hashtable.h" + +_Py_IDENTIFIER(read); +_Py_IDENTIFIER(readinto); +_Py_IDENTIFIER(write); + /*[clinic input] module marshal [clinic start generated code]*/ @@ -685,7 +690,6 @@ r_string(Py_ssize_t n, RFILE *p) read = fread(p->buf, 1, n, p->fp); } else { - _Py_IDENTIFIER(readinto); PyObject *res, *mview; Py_buffer buf; @@ -1648,7 +1652,6 @@ marshal_dump_impl(PyObject *module, PyObject *value, PyObject *file, /* XXX Quick hack -- need to do this differently */ PyObject *s; PyObject *res; - _Py_IDENTIFIER(write); s = PyMarshal_WriteObjectToString(value, version); if (s == NULL) @@ -1680,7 +1683,6 @@ marshal_load(PyObject *module, PyObject *file) /*[clinic end generated code: output=f8e5c33233566344 input=c85c2b594cd8124a]*/ { PyObject *data, *result; - _Py_IDENTIFIER(read); RFILE rf; /* diff --git a/Python/pylifecycle.c b/Python/pylifecycle.c index e89152637fe145..c846809ce8d9b4 100644 --- a/Python/pylifecycle.c +++ b/Python/pylifecycle.c @@ -45,12 +45,18 @@ extern PyTypeObject PyWindowsConsoleIO_Type; #define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type)) #endif +_Py_IDENTIFIER(_shutdown); _Py_IDENTIFIER(flush); +_Py_IDENTIFIER(isatty); +_Py_IDENTIFIER(mode); _Py_IDENTIFIER(name); +_Py_IDENTIFIER(open); +_Py_IDENTIFIER(raw); _Py_IDENTIFIER(stdin); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); _Py_IDENTIFIER(threading); +_Py_IDENTIFIER(TextIOWrapper); #ifdef __cplusplus extern "C" { @@ -1690,10 +1696,6 @@ create_stdio(const _PyCoreConfig *config, PyObject* io, const char* newline; PyObject *line_buffering, *write_through; int buffering, isatty; - _Py_IDENTIFIER(open); - _Py_IDENTIFIER(isatty); - _Py_IDENTIFIER(TextIOWrapper); - _Py_IDENTIFIER(mode); const int buffered_stdio = config->buffered_stdio; if (!is_valid_fd(fd)) @@ -1720,7 +1722,6 @@ create_stdio(const _PyCoreConfig *config, PyObject* io, goto error; if (buffering) { - _Py_IDENTIFIER(raw); raw = _PyObject_GetAttrId(buf, &PyId_raw); if (raw == NULL) goto error; @@ -2052,7 +2053,7 @@ static void _Py_NO_RETURN fatal_error(const char *prefix, const char *msg, int status) { const int fd = fileno(stderr); - static int reentrant = 0; + static int reentrant = 0; // Static is okay here (process-global). if (reentrant) { /* Py_FatalError() caused a second fatal error. @@ -2183,7 +2184,6 @@ call_py_exitfuncs(PyInterpreterState *istate) static void wait_for_thread_shutdown(void) { - _Py_IDENTIFIER(_shutdown); PyObject *result; PyObject *threading = _PyImport_GetModuleId(&PyId_threading); if (threading == NULL) { diff --git a/Python/pythonrun.c b/Python/pythonrun.c index bc131fd7e5ec2b..21c5ecbe579f2e 100644 --- a/Python/pythonrun.c +++ b/Python/pythonrun.c @@ -39,17 +39,27 @@ #include "windows.h" #endif +_Py_IDENTIFIER(__main__); +_Py_IDENTIFIER(__module__); _Py_IDENTIFIER(builtins); +_Py_IDENTIFIER(code); +_Py_IDENTIFIER(encoding); _Py_IDENTIFIER(excepthook); +_Py_IDENTIFIER(filename); _Py_IDENTIFIER(flush); _Py_IDENTIFIER(last_traceback); _Py_IDENTIFIER(last_type); _Py_IDENTIFIER(last_value); +_Py_IDENTIFIER(lineno); +_Py_IDENTIFIER(msg); +_Py_IDENTIFIER(offset); +_Py_IDENTIFIER(print_file_and_line); _Py_IDENTIFIER(ps1); _Py_IDENTIFIER(ps2); _Py_IDENTIFIER(stdin); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); +_Py_IDENTIFIER(text); _Py_static_string(PyId_string, ""); #ifdef __cplusplus @@ -185,8 +195,6 @@ PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename, PyArena *arena; const char *ps1 = "", *ps2 = "", *enc = NULL; int errcode = 0; - _Py_IDENTIFIER(encoding); - _Py_IDENTIFIER(__main__); mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */ if (mod_name == NULL) { @@ -473,11 +481,6 @@ parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, { int hold; PyObject *v; - _Py_IDENTIFIER(msg); - _Py_IDENTIFIER(filename); - _Py_IDENTIFIER(lineno); - _Py_IDENTIFIER(offset); - _Py_IDENTIFIER(text); *message = NULL; *filename = NULL; @@ -604,7 +607,6 @@ handle_system_exit(void) goto done; if (PyExceptionInstance_Check(value)) { /* The error code should be in the `code' attribute. */ - _Py_IDENTIFIER(code); PyObject *code = _PyObject_GetAttrId(value, &PyId_code); if (code) { Py_DECREF(value); @@ -727,7 +729,6 @@ print_exception(PyObject *f, PyObject *value) { int err = 0; PyObject *type, *tb; - _Py_IDENTIFIER(print_file_and_line); if (!PyExceptionInstance_Check(value)) { err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); @@ -783,7 +784,6 @@ print_exception(PyObject *f, PyObject *value) else { PyObject* moduleName; const char *className; - _Py_IDENTIFIER(__module__); assert(PyExceptionClass_Check(type)); className = PyExceptionClass_Name(type); if (className != NULL) { diff --git a/Python/pytime.c b/Python/pytime.c index 9ff300699f04af..070382b2ac447b 100644 --- a/Python/pytime.c +++ b/Python/pytime.c @@ -800,8 +800,8 @@ pymonotonic(_PyTime_t *tp, _Py_clock_info_t *info, int raise) } #elif defined(__APPLE__) - static mach_timebase_info_data_t timebase; - static uint64_t t0 = 0; + static mach_timebase_info_data_t timebase; // Static is okay here (process-global?). + static uint64_t t0 = 0; // Static is okay here (process-global?). uint64_t ticks; if (timebase.denom == 0) { @@ -938,8 +938,8 @@ _PyTime_GetMonotonicClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info) static int win_perf_counter(_PyTime_t *tp, _Py_clock_info_t *info) { - static LONGLONG frequency = 0; - static LONGLONG t0 = 0; + static LONGLONG frequency = 0; // Static is okay here (process-global?). + static LONGLONG t0 = 0; // Static is okay here (process-global?). LARGE_INTEGER now; LONGLONG ticksll; _PyTime_t ticks; diff --git a/Python/sysmodule.c b/Python/sysmodule.c index 1290164edbf68d..60ed5a6bfb930d 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -264,6 +264,8 @@ sys_displayhook_unencodable(PyObject *outf, PyObject *o) return ret; } +static PyObject *newline = NULL; + /*[clinic input] sys.displayhook @@ -279,7 +281,6 @@ sys_displayhook(PyObject *module, PyObject *o) { PyObject *outf; PyObject *builtins; - static PyObject *newline = NULL; int err; builtins = _PyImport_GetModuleId(&PyId_builtins); @@ -481,7 +482,7 @@ static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NUL static int trace_init(void) { - static const char * const whatnames[8] = { + static const char * const whatnames[8] = { // Static is okay here (immutable data). "call", "exception", "line", "return", "c_call", "c_exception", "c_return", "opcode" @@ -909,12 +910,12 @@ static PyStructSequence_Desc asyncgen_hooks_desc = { static PyObject * sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw) { - static char *keywords[] = {"firstiter", "finalizer", NULL}; + static char *kwlist[] = {"firstiter", "finalizer", NULL}; PyObject *firstiter = NULL; PyObject *finalizer = NULL; if (!PyArg_ParseTupleAndKeywords( - args, kw, "|OO", keywords, + args, kw, "|OO", kwlist, &firstiter, &finalizer)) { return NULL; } diff --git a/Python/thread_pthread.h b/Python/thread_pthread.h index 87c98d3e93cb77..c5fa327f1a3c96 100644 --- a/Python/thread_pthread.h +++ b/Python/thread_pthread.h @@ -118,11 +118,14 @@ do { \ // NULL when pthread_condattr_setclock(CLOCK_MONOTONIC) is not supported. static pthread_condattr_t *condattr_monotonic = NULL; +#ifdef CONDATTR_MONOTONIC +static pthread_condattr_t ca; +#endif + static void init_condattr() { #ifdef CONDATTR_MONOTONIC - static pthread_condattr_t ca; pthread_condattr_init(&ca); if (pthread_condattr_setclock(&ca, CLOCK_MONOTONIC) == 0) { condattr_monotonic = &ca; // Use monotonic clock