diff options
author | Eric Snow <ericsnowcurrently@gmail.com> | 2022-02-08 20:39:07 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-02-08 20:39:07 (GMT) |
commit | 81c72044a181dbbfbf689d7a977d0d99090f26a8 (patch) | |
tree | 14329746bd6f179cf2ae7c9818e1ae881eb46360 /Python | |
parent | c018d3037b5b62e6d48d5985d1a37b91762fbffb (diff) | |
download | cpython-81c72044a181dbbfbf689d7a977d0d99090f26a8.zip cpython-81c72044a181dbbfbf689d7a977d0d99090f26a8.tar.gz cpython-81c72044a181dbbfbf689d7a977d0d99090f26a8.tar.bz2 |
bpo-46541: Replace core use of _Py_IDENTIFIER() with statically initialized global objects. (gh-30928)
We're no longer using _Py_IDENTIFIER() (or _Py_static_string()) in any core CPython code. It is still used in a number of non-builtin stdlib modules.
The replacement is: PyUnicodeObject (not pointer) fields under _PyRuntimeState, statically initialized as part of _PyRuntime. A new _Py_GET_GLOBAL_IDENTIFIER() macro facilitates lookup of the fields (along with _Py_GET_GLOBAL_STRING() for non-identifier strings).
https://bugs.python.org/issue46541#msg411799 explains the rationale for this change.
The core of the change is in:
* (new) Include/internal/pycore_global_strings.h - the declarations for the global strings, along with the macros
* Include/internal/pycore_runtime_init.h - added the static initializers for the global strings
* Include/internal/pycore_global_objects.h - where the struct in pycore_global_strings.h is hooked into _PyRuntimeState
* Tools/scripts/generate_global_objects.py - added generation of the global string declarations and static initializers
I've also added a --check flag to generate_global_objects.py (along with make check-global-objects) to check for unused global strings. That check is added to the PR CI config.
The remainder of this change updates the core code to use _Py_GET_GLOBAL_IDENTIFIER() instead of _Py_IDENTIFIER() and the related _Py*Id functions (likewise for _Py_GET_GLOBAL_STRING() instead of _Py_static_string()). This includes adding a few functions where there wasn't already an alternative to _Py*Id(), replacing the _Py_Identifier * parameter with PyObject *.
The following are not changed (yet):
* stop using _Py_IDENTIFIER() in the stdlib modules
* (maybe) get rid of _Py_IDENTIFIER(), etc. entirely -- this may not be doable as at least one package on PyPI using this (private) API
* (maybe) intern the strings during runtime init
https://bugs.python.org/issue46541
Diffstat (limited to 'Python')
-rw-r--r-- | Python/_warnings.c | 263 | ||||
-rw-r--r-- | Python/ast_opt.c | 11 | ||||
-rw-r--r-- | Python/bltinmodule.c | 72 | ||||
-rw-r--r-- | Python/ceval.c | 90 | ||||
-rw-r--r-- | Python/codecs.c | 3 | ||||
-rw-r--r-- | Python/compile.c | 106 | ||||
-rw-r--r-- | Python/errors.c | 53 | ||||
-rw-r--r-- | Python/import.c | 90 | ||||
-rw-r--r-- | Python/importdl.c | 6 | ||||
-rw-r--r-- | Python/marshal.c | 9 | ||||
-rw-r--r-- | Python/pylifecycle.c | 68 | ||||
-rw-r--r-- | Python/pythonrun.c | 123 | ||||
-rw-r--r-- | Python/specialize.c | 22 | ||||
-rw-r--r-- | Python/sysmodule.c | 88 | ||||
-rw-r--r-- | Python/traceback.c | 26 |
15 files changed, 431 insertions, 599 deletions
diff --git a/Python/_warnings.c b/Python/_warnings.c index cf2110d..a47e5fe 100644 --- a/Python/_warnings.c +++ b/Python/_warnings.c @@ -14,30 +14,45 @@ 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(stderr); -#ifndef Py_DEBUG -_Py_IDENTIFIER(default); -_Py_IDENTIFIER(ignore); -#endif - /*************************************************************************/ typedef struct _warnings_runtime_state WarningsState; -_Py_IDENTIFIER(__name__); - -/* Given a module object, get its per-module state. */ -static WarningsState * -warnings_get_state(void) +static inline int +check_interp(PyInterpreterState *interp) { - PyInterpreterState *interp = _PyInterpreterState_GET(); if (interp == NULL) { PyErr_SetString(PyExc_RuntimeError, "warnings_get_state: could not identify " "current interpreter"); + return 0; + } + return 1; +} + +static inline PyInterpreterState * +get_current_interp(void) +{ + PyInterpreterState *interp = _PyInterpreterState_GET(); + return check_interp(interp) ? interp : NULL; +} + +static inline PyThreadState * +get_current_tstate(void) +{ + PyThreadState *tstate = _PyThreadState_GET(); + if (tstate == NULL) { + (void)check_interp(NULL); return NULL; } + return check_interp(tstate->interp) ? tstate : NULL; +} + +/* Given a module object, get its per-module state. */ +static WarningsState * +warnings_get_state(PyInterpreterState *interp) +{ return &interp->warnings; } @@ -52,13 +67,9 @@ warnings_clear_state(WarningsState *st) #ifndef Py_DEBUG static PyObject * -create_filter(PyObject *category, _Py_Identifier *id, const char *modname) +create_filter(PyObject *category, PyObject *action_str, const char *modname) { PyObject *modname_obj = NULL; - PyObject *action_str = _PyUnicode_FromId(id); - if (action_str == NULL) { - return NULL; - } /* Default to "no module name" for initial filter set */ if (modname != NULL) { @@ -79,7 +90,7 @@ create_filter(PyObject *category, _Py_Identifier *id, const char *modname) #endif static PyObject * -init_filters(void) +init_filters(PyInterpreterState *interp) { #ifdef Py_DEBUG /* Py_DEBUG builds show all warnings by default */ @@ -92,16 +103,15 @@ init_filters(void) } size_t pos = 0; /* Post-incremented in each use. */ - PyList_SET_ITEM(filters, pos++, - create_filter(PyExc_DeprecationWarning, &PyId_default, "__main__")); - PyList_SET_ITEM(filters, pos++, - create_filter(PyExc_DeprecationWarning, &PyId_ignore, NULL)); - PyList_SET_ITEM(filters, pos++, - create_filter(PyExc_PendingDeprecationWarning, &PyId_ignore, NULL)); - PyList_SET_ITEM(filters, pos++, - create_filter(PyExc_ImportWarning, &PyId_ignore, NULL)); - PyList_SET_ITEM(filters, pos++, - create_filter(PyExc_ResourceWarning, &PyId_ignore, NULL)); +#define ADD(TYPE, ACTION, MODNAME) \ + PyList_SET_ITEM(filters, pos++, \ + create_filter(TYPE, &_Py_ID(ACTION), MODNAME)); + ADD(PyExc_DeprecationWarning, default, "__main__"); + ADD(PyExc_DeprecationWarning, ignore, NULL); + ADD(PyExc_PendingDeprecationWarning, ignore, NULL); + ADD(PyExc_ImportWarning, ignore, NULL); + ADD(PyExc_ResourceWarning, ignore, NULL); +#undef ADD for (size_t x = 0; x < pos; x++) { if (PyList_GET_ITEM(filters, x) == NULL) { @@ -120,7 +130,7 @@ _PyWarnings_InitState(PyInterpreterState *interp) WarningsState *st = &interp->warnings; if (st->filters == NULL) { - st->filters = init_filters(); + st->filters = init_filters(interp); if (st->filters == NULL) { return -1; } @@ -148,10 +158,9 @@ _PyWarnings_InitState(PyInterpreterState *interp) /*************************************************************************/ static int -check_matched(PyObject *obj, PyObject *arg) +check_matched(PyInterpreterState *interp, PyObject *obj, PyObject *arg) { PyObject *result; - _Py_IDENTIFIER(match); int rc; /* A 'None' filter always matches */ @@ -168,7 +177,7 @@ check_matched(PyObject *obj, PyObject *arg) } /* Otherwise assume a regex filter and call its match() method */ - result = _PyObject_CallMethodIdOneArg(obj, &PyId_match, arg); + result = PyObject_CallMethodOneArg(obj, &_Py_ID(match), arg); if (result == NULL) return -1; @@ -177,25 +186,21 @@ check_matched(PyObject *obj, PyObject *arg) return rc; } +#define GET_WARNINGS_ATTR(interp, attr, try_import) \ + get_warnings_attr(interp, &_Py_ID(attr), try_import) + /* Returns a new reference. A NULL return value can mean false or an error. */ static PyObject * -get_warnings_attr(_Py_Identifier *attr_id, int try_import) +get_warnings_attr(PyInterpreterState *interp, PyObject *attr, int try_import) { - PyObject *warnings_str; PyObject *warnings_module, *obj; - _Py_IDENTIFIER(warnings); - - warnings_str = _PyUnicode_FromId(&PyId_warnings); - if (warnings_str == NULL) { - return NULL; - } /* don't try to import after the start of the Python finallization */ if (try_import && !_Py_IsFinalizing()) { - warnings_module = PyImport_Import(warnings_str); + warnings_module = PyImport_Import(&_Py_ID(warnings)); if (warnings_module == NULL) { /* Fallback to the C implementation if we cannot get the Python implementation */ @@ -210,27 +215,31 @@ get_warnings_attr(_Py_Identifier *attr_id, int try_import) gone, then we can't even use PyImport_GetModule without triggering an interpreter abort. */ - if (!_PyInterpreterState_GET()->modules) { + if (!interp->modules) { return NULL; } - warnings_module = PyImport_GetModule(warnings_str); + warnings_module = PyImport_GetModule(&_Py_ID(warnings)); if (warnings_module == NULL) return NULL; } - (void)_PyObject_LookupAttrId(warnings_module, attr_id, &obj); + (void)_PyObject_LookupAttr(warnings_module, attr, &obj); Py_DECREF(warnings_module); return obj; } static PyObject * -get_once_registry(WarningsState *st) +get_once_registry(PyInterpreterState *interp) { PyObject *registry; - _Py_IDENTIFIER(onceregistry); - registry = get_warnings_attr(&PyId_onceregistry, 0); + WarningsState *st = warnings_get_state(interp); + if (st == NULL) { + return NULL; + } + + registry = GET_WARNINGS_ATTR(interp, onceregistry, 0); if (registry == NULL) { if (PyErr_Occurred()) return NULL; @@ -251,12 +260,16 @@ get_once_registry(WarningsState *st) static PyObject * -get_default_action(WarningsState *st) +get_default_action(PyInterpreterState *interp) { PyObject *default_action; - _Py_IDENTIFIER(defaultaction); - default_action = get_warnings_attr(&PyId_defaultaction, 0); + WarningsState *st = warnings_get_state(interp); + if (st == NULL) { + return NULL; + } + + default_action = GET_WARNINGS_ATTR(interp, defaultaction, 0); if (default_action == NULL) { if (PyErr_Occurred()) { return NULL; @@ -279,19 +292,19 @@ get_default_action(WarningsState *st) /* The item is a new reference. */ static PyObject* -get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno, +get_filter(PyInterpreterState *interp, PyObject *category, + PyObject *text, Py_ssize_t lineno, PyObject *module, PyObject **item) { PyObject *action; Py_ssize_t i; PyObject *warnings_filters; - _Py_IDENTIFIER(filters); - WarningsState *st = warnings_get_state(); + WarningsState *st = warnings_get_state(interp); if (st == NULL) { return NULL; } - warnings_filters = get_warnings_attr(&PyId_filters, 0); + warnings_filters = GET_WARNINGS_ATTR(interp, filters, 0); if (warnings_filters == NULL) { if (PyErr_Occurred()) return NULL; @@ -336,13 +349,13 @@ get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno, return NULL; } - good_msg = check_matched(msg, text); + good_msg = check_matched(interp, msg, text); if (good_msg == -1) { Py_DECREF(tmp_item); return NULL; } - good_mod = check_matched(mod, module); + good_mod = check_matched(interp, mod, module); if (good_mod == -1) { Py_DECREF(tmp_item); return NULL; @@ -368,7 +381,7 @@ get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno, Py_DECREF(tmp_item); } - action = get_default_action(st); + action = get_default_action(interp); if (action != NULL) { Py_INCREF(Py_None); *item = Py_None; @@ -380,19 +393,19 @@ get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno, static int -already_warned(PyObject *registry, PyObject *key, int should_set) +already_warned(PyInterpreterState *interp, PyObject *registry, PyObject *key, + int should_set) { PyObject *version_obj, *already_warned; - _Py_IDENTIFIER(version); if (key == NULL) return -1; - WarningsState *st = warnings_get_state(); + WarningsState *st = warnings_get_state(interp); if (st == NULL) { return -1; } - version_obj = _PyDict_GetItemIdWithError(registry, &PyId_version); + version_obj = _PyDict_GetItemWithError(registry, &_Py_ID(version)); if (version_obj == NULL || !PyLong_CheckExact(version_obj) || PyLong_AsLong(version_obj) != st->filters_version) @@ -404,7 +417,7 @@ already_warned(PyObject *registry, PyObject *key, int should_set) version_obj = PyLong_FromLong(st->filters_version); if (version_obj == NULL) return -1; - if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) { + if (PyDict_SetItem(registry, &_Py_ID(version), version_obj) < 0) { Py_DECREF(version_obj); return -1; } @@ -463,8 +476,8 @@ normalize_module(PyObject *filename) } static int -update_registry(PyObject *registry, PyObject *text, PyObject *category, - int add_zero) +update_registry(PyInterpreterState *interp, PyObject *registry, PyObject *text, + PyObject *category, int add_zero) { PyObject *altkey; int rc; @@ -474,14 +487,14 @@ update_registry(PyObject *registry, PyObject *text, PyObject *category, else altkey = PyTuple_Pack(2, text, category); - rc = already_warned(registry, altkey, 1); + rc = already_warned(interp, registry, altkey, 1); Py_XDECREF(altkey); return rc; } static void -show_warning(PyObject *filename, int lineno, PyObject *text, - PyObject *category, PyObject *sourceline) +show_warning(PyThreadState *tstate, PyObject *filename, int lineno, + PyObject *text, PyObject *category, PyObject *sourceline) { PyObject *f_stderr; PyObject *name; @@ -489,12 +502,12 @@ show_warning(PyObject *filename, int lineno, PyObject *text, PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno); - name = _PyObject_GetAttrId(category, &PyId___name__); + name = PyObject_GetAttr(category, &_Py_ID(__name__)); if (name == NULL) { goto error; } - f_stderr = _PySys_GetObjectId(&PyId_stderr); + f_stderr = _PySys_GetAttr(tstate, &_Py_ID(stderr)); if (f_stderr == NULL) { fprintf(stderr, "lost sys.stderr\n"); goto error; @@ -553,22 +566,22 @@ error: } static int -call_show_warning(PyObject *category, PyObject *text, PyObject *message, +call_show_warning(PyThreadState *tstate, PyObject *category, + PyObject *text, PyObject *message, PyObject *filename, int lineno, PyObject *lineno_obj, PyObject *sourceline, PyObject *source) { PyObject *show_fn, *msg, *res, *warnmsg_cls = NULL; - _Py_IDENTIFIER(_showwarnmsg); - _Py_IDENTIFIER(WarningMessage); + PyInterpreterState *interp = tstate->interp; /* If the source parameter is set, try to get the Python implementation. The Python implementation is able to log the traceback where the source was allocated, whereas the C implementation doesn't. */ - show_fn = get_warnings_attr(&PyId__showwarnmsg, source != NULL); + show_fn = GET_WARNINGS_ATTR(interp, _showwarnmsg, source != NULL); if (show_fn == NULL) { if (PyErr_Occurred()) return -1; - show_warning(filename, lineno, text, category, sourceline); + show_warning(tstate, filename, lineno, text, category, sourceline); return 0; } @@ -578,7 +591,7 @@ call_show_warning(PyObject *category, PyObject *text, PyObject *message, goto error; } - warnmsg_cls = get_warnings_attr(&PyId_WarningMessage, 0); + warnmsg_cls = GET_WARNINGS_ATTR(interp, WarningMessage, 0); if (warnmsg_cls == NULL) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, @@ -610,7 +623,7 @@ error: } static PyObject * -warn_explicit(PyObject *category, PyObject *message, +warn_explicit(PyThreadState *tstate, PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry, PyObject *sourceline, PyObject *source) @@ -619,6 +632,7 @@ warn_explicit(PyObject *category, PyObject *message, PyObject *item = NULL; PyObject *action; int rc; + PyInterpreterState *interp = tstate->interp; /* module can be None if a warning is emitted late during Python shutdown. In this case, the Python warnings module was probably unloaded, filters @@ -674,7 +688,7 @@ warn_explicit(PyObject *category, PyObject *message, goto cleanup; if ((registry != NULL) && (registry != Py_None)) { - rc = already_warned(registry, key, 0); + rc = already_warned(interp, registry, key, 0); if (rc == -1) goto cleanup; else if (rc == 1) @@ -682,7 +696,7 @@ warn_explicit(PyObject *category, PyObject *message, /* Else this warning hasn't been generated before. */ } - action = get_filter(category, text, lineno, module, &item); + action = get_filter(interp, category, text, lineno, module, &item); if (action == NULL) goto cleanup; @@ -707,21 +721,17 @@ warn_explicit(PyObject *category, PyObject *message, if (_PyUnicode_EqualToASCIIString(action, "once")) { if (registry == NULL || registry == Py_None) { - WarningsState *st = warnings_get_state(); - if (st == NULL) { - goto cleanup; - } - registry = get_once_registry(st); + registry = get_once_registry(interp); if (registry == NULL) goto cleanup; } /* WarningsState.once_registry[(text, category)] = 1 */ - rc = update_registry(registry, text, category, 0); + rc = update_registry(interp, registry, text, category, 0); } else if (_PyUnicode_EqualToASCIIString(action, "module")) { /* registry[(text, category, 0)] = 1 */ if (registry != NULL && registry != Py_None) - rc = update_registry(registry, text, category, 0); + rc = update_registry(interp, registry, text, category, 0); } else if (!_PyUnicode_EqualToASCIIString(action, "default")) { PyErr_Format(PyExc_RuntimeError, @@ -734,8 +744,8 @@ warn_explicit(PyObject *category, PyObject *message, if (rc == 1) /* Already warned for this module. */ goto return_none; if (rc == 0) { - if (call_show_warning(category, text, message, filename, lineno, - lineno_obj, sourceline, source) < 0) + if (call_show_warning(tstate, category, text, message, filename, + lineno, lineno_obj, sourceline, source) < 0) goto cleanup; } else /* if (rc == -1) */ @@ -827,11 +837,14 @@ static int setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno, PyObject **module, PyObject **registry) { - _Py_IDENTIFIER(__warningregistry__); PyObject *globals; /* Setup globals, filename and lineno. */ - PyThreadState *tstate = _PyThreadState_GET(); + PyThreadState *tstate = get_current_tstate(); + if (tstate == NULL) { + return 0; + } + PyInterpreterState *interp = tstate->interp; PyFrameObject *f = PyThreadState_GetFrame(tstate); // Stack level comparisons to Python code is off by one as there is no // warnings-related stack level to avoid. @@ -849,7 +862,7 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno, } if (f == NULL) { - globals = tstate->interp->sysdict; + globals = interp->sysdict; *filename = PyUnicode_FromString("sys"); *lineno = 1; } @@ -866,7 +879,7 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno, /* Setup registry. */ assert(globals != NULL); assert(PyDict_Check(globals)); - *registry = _PyDict_GetItemIdWithError(globals, &PyId___warningregistry__); + *registry = _PyDict_GetItemWithError(globals, &_Py_ID(__warningregistry__)); if (*registry == NULL) { int rc; @@ -877,7 +890,7 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno, if (*registry == NULL) goto handle_error; - rc = _PyDict_SetItemId(globals, &PyId___warningregistry__, *registry); + rc = PyDict_SetItem(globals, &_Py_ID(__warningregistry__), *registry); if (rc < 0) goto handle_error; } @@ -885,7 +898,7 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno, Py_INCREF(*registry); /* Setup module. */ - *module = _PyDict_GetItemIdWithError(globals, &PyId___name__); + *module = _PyDict_GetItemWithError(globals, &_Py_ID(__name__)); if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) { Py_INCREF(*module); } @@ -943,10 +956,15 @@ do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level, PyObject *filename, *module, *registry, *res; int lineno; + PyThreadState *tstate = get_current_tstate(); + if (tstate == NULL) { + return NULL; + } + if (!setup_context(stack_level, &filename, &lineno, &module, ®istry)) return NULL; - res = warn_explicit(category, message, filename, lineno, module, registry, + res = warn_explicit(tstate, category, message, filename, lineno, module, registry, NULL, source); Py_DECREF(filename); Py_DECREF(registry); @@ -977,10 +995,8 @@ warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category, } static PyObject * -get_source_line(PyObject *module_globals, int lineno) +get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno) { - _Py_IDENTIFIER(get_source); - _Py_IDENTIFIER(__loader__); PyObject *loader; PyObject *module_name; PyObject *get_source; @@ -989,12 +1005,12 @@ get_source_line(PyObject *module_globals, int lineno) PyObject *source_line; /* Check/get the requisite pieces needed for the loader. */ - loader = _PyDict_GetItemIdWithError(module_globals, &PyId___loader__); + loader = _PyDict_GetItemWithError(module_globals, &_Py_ID(__loader__)); if (loader == NULL) { return NULL; } Py_INCREF(loader); - module_name = _PyDict_GetItemIdWithError(module_globals, &PyId___name__); + module_name = _PyDict_GetItemWithError(module_globals, &_Py_ID(__name__)); if (!module_name) { Py_DECREF(loader); return NULL; @@ -1002,7 +1018,7 @@ get_source_line(PyObject *module_globals, int lineno) Py_INCREF(module_name); /* Make sure the loader implements the optional get_source() method. */ - (void)_PyObject_LookupAttrId(loader, &PyId_get_source, &get_source); + (void)_PyObject_LookupAttr(loader, &_Py_ID(get_source), &get_source); Py_DECREF(loader); if (!get_source) { Py_DECREF(module_name); @@ -1056,6 +1072,11 @@ warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds) ®istry, &module_globals, &sourceobj)) return NULL; + PyThreadState *tstate = get_current_tstate(); + if (tstate == NULL) { + return NULL; + } + if (module_globals && module_globals != Py_None) { if (!PyDict_Check(module_globals)) { PyErr_Format(PyExc_TypeError, @@ -1064,12 +1085,12 @@ warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds) return NULL; } - source_line = get_source_line(module_globals, lineno); + source_line = get_source_line(tstate->interp, module_globals, lineno); if (source_line == NULL && PyErr_Occurred()) { return NULL; } } - returned = warn_explicit(category, message, filename, lineno, module, + returned = warn_explicit(tstate, category, message, filename, lineno, module, registry, source_line, sourceobj); Py_XDECREF(source_line); return returned; @@ -1078,7 +1099,11 @@ warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds) static PyObject * warnings_filters_mutated(PyObject *self, PyObject *args) { - WarningsState *st = warnings_get_state(); + PyInterpreterState *interp = get_current_interp(); + if (interp == NULL) { + return NULL; + } + WarningsState *st = warnings_get_state(interp); if (st == NULL) { return NULL; } @@ -1208,7 +1233,11 @@ PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *res; if (category == NULL) category = PyExc_RuntimeWarning; - res = warn_explicit(category, message, filename, lineno, + PyThreadState *tstate = get_current_tstate(); + if (tstate == NULL) { + return -1; + } + res = warn_explicit(tstate, category, message, filename, lineno, module, registry, NULL, NULL); if (res == NULL) return -1; @@ -1272,12 +1301,15 @@ PyErr_WarnExplicitFormat(PyObject *category, message = PyUnicode_FromFormatV(format, vargs); if (message != NULL) { PyObject *res; - res = warn_explicit(category, message, filename, lineno, - module, registry, NULL, NULL); - Py_DECREF(message); - if (res != NULL) { - Py_DECREF(res); - ret = 0; + PyThreadState *tstate = get_current_tstate(); + if (tstate != NULL) { + res = warn_explicit(tstate, category, message, filename, lineno, + module, registry, NULL, NULL); + Py_DECREF(message); + if (res != NULL) { + Py_DECREF(res); + ret = 0; + } } } va_end(vargs); @@ -1309,9 +1341,10 @@ _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); + PyInterpreterState *interp = _PyInterpreterState_GET(); + assert(interp != NULL); + PyObject *fn = GET_WARNINGS_ATTR(interp, _warn_unawaited_coroutine, 1); if (fn) { PyObject *res = PyObject_CallOneArg(fn, coro); Py_DECREF(fn); @@ -1352,7 +1385,11 @@ static PyMethodDef warnings_functions[] = { static int warnings_module_exec(PyObject *module) { - WarningsState *st = warnings_get_state(); + PyInterpreterState *interp = get_current_interp(); + if (interp == NULL) { + return -1; + } + WarningsState *st = warnings_get_state(interp); if (st == NULL) { return -1; } diff --git a/Python/ast_opt.c b/Python/ast_opt.c index 967e75d..2911370 100644 --- a/Python/ast_opt.c +++ b/Python/ast_opt.c @@ -268,15 +268,8 @@ parse_literal(PyObject *fmt, Py_ssize_t *ppos, PyArena *arena) PyObject *str = PyUnicode_Substring(fmt, start, pos); /* str = str.replace('%%', '%') */ if (str && has_percents) { - _Py_static_string(PyId_double_percent, "%%"); - _Py_static_string(PyId_percent, "%"); - PyObject *double_percent = _PyUnicode_FromId(&PyId_double_percent); - PyObject *percent = _PyUnicode_FromId(&PyId_percent); - if (!double_percent || !percent) { - Py_DECREF(str); - return NULL; - } - Py_SETREF(str, PyUnicode_Replace(str, double_percent, percent, -1)); + Py_SETREF(str, PyUnicode_Replace(str, &_Py_STR(dbl_percent), + &_Py_STR(percent), -1)); } if (!str) { return NULL; diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index ed61209..b253f88 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -11,21 +11,6 @@ #include "pycore_tuple.h" // _PyTuple_FromArray() #include "pycore_ceval.h" // _PyEval_Vector() -_Py_IDENTIFIER(__builtins__); -_Py_IDENTIFIER(__dict__); -_Py_IDENTIFIER(__prepare__); -_Py_IDENTIFIER(__round__); -_Py_IDENTIFIER(__mro_entries__); -_Py_IDENTIFIER(encoding); -_Py_IDENTIFIER(errors); -_Py_IDENTIFIER(fileno); -_Py_IDENTIFIER(flush); -_Py_IDENTIFIER(metaclass); -_Py_IDENTIFIER(sort); -_Py_IDENTIFIER(stdin); -_Py_IDENTIFIER(stdout); -_Py_IDENTIFIER(stderr); - #include "clinic/bltinmodule.c.h" static PyObject* @@ -47,7 +32,7 @@ update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs) } continue; } - if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) { + if (_PyObject_LookupAttr(base, &_Py_ID(__mro_entries__), &meth) < 0) { goto error; } if (!meth) { @@ -148,10 +133,10 @@ builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs, goto error; } - meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass); + meta = _PyDict_GetItemWithError(mkw, &_Py_ID(metaclass)); if (meta != NULL) { Py_INCREF(meta); - if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) { + if (PyDict_DelItem(mkw, &_Py_ID(metaclass)) < 0) { goto error; } /* metaclass is explicitly given, check if it's indeed a class */ @@ -191,7 +176,7 @@ builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs, } /* else: meta is not a class, so we cannot do the metaclass calculation, so we will use the explicitly given object as it is */ - if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) { + if (_PyObject_LookupAttr(meta, &_Py_ID(__prepare__), &prep) < 0) { ns = NULL; } else if (prep == NULL) { @@ -946,10 +931,9 @@ builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals, return NULL; } - int r = _PyDict_ContainsId(globals, &PyId___builtins__); + int r = PyDict_Contains(globals, &_Py_ID(__builtins__)); if (r == 0) { - r = _PyDict_SetItemId(globals, &PyId___builtins__, - PyEval_GetBuiltins()); + r = PyDict_SetItem(globals, &_Py_ID(__builtins__), PyEval_GetBuiltins()); } if (r < 0) { return NULL; @@ -1034,10 +1018,9 @@ builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals, Py_TYPE(locals)->tp_name); return NULL; } - int r = _PyDict_ContainsId(globals, &PyId___builtins__); + int r = PyDict_Contains(globals, &_Py_ID(__builtins__)); if (r == 0) { - r = _PyDict_SetItemId(globals, &PyId___builtins__, - PyEval_GetBuiltins()); + r = PyDict_SetItem(globals, &_Py_ID(__builtins__), PyEval_GetBuiltins()); } if (r < 0) { return NULL; @@ -1960,7 +1943,8 @@ builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep, int i, err; if (file == Py_None) { - file = _PySys_GetObjectId(&PyId_stdout); + PyThreadState *tstate = _PyThreadState_GET(); + file = _PySys_GetAttr(tstate, &_Py_ID(stdout)); if (file == NULL) { PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); return NULL; @@ -2020,7 +2004,7 @@ builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep, } if (flush) { - PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush); + PyObject *tmp = PyObject_CallMethodNoArgs(file, &_Py_ID(flush)); if (tmp == NULL) { return NULL; } @@ -2050,9 +2034,13 @@ static PyObject * builtin_input_impl(PyObject *module, PyObject *prompt) /*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/ { - PyObject *fin = _PySys_GetObjectId(&PyId_stdin); - PyObject *fout = _PySys_GetObjectId(&PyId_stdout); - PyObject *ferr = _PySys_GetObjectId(&PyId_stderr); + PyThreadState *tstate = _PyThreadState_GET(); + PyObject *fin = _PySys_GetAttr( + tstate, &_Py_ID(stdin)); + PyObject *fout = _PySys_GetAttr( + tstate, &_Py_ID(stdout)); + PyObject *ferr = _PySys_GetAttr( + tstate, &_Py_ID(stderr)); PyObject *tmp; long fd; int tty; @@ -2079,7 +2067,7 @@ builtin_input_impl(PyObject *module, PyObject *prompt) } /* First of all, flush stderr */ - tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush); + tmp = PyObject_CallMethodNoArgs(ferr, &_Py_ID(flush)); if (tmp == NULL) PyErr_Clear(); else @@ -2088,7 +2076,7 @@ builtin_input_impl(PyObject *module, PyObject *prompt) /* We should only use (GNU) readline if Python's sys.stdin and sys.stdout are the same as C's stdin and stdout, because we need to pass it those. */ - tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno); + tmp = PyObject_CallMethodNoArgs(fin, &_Py_ID(fileno)); if (tmp == NULL) { PyErr_Clear(); tty = 0; @@ -2101,7 +2089,7 @@ builtin_input_impl(PyObject *module, PyObject *prompt) tty = fd == fileno(stdin) && isatty(fd); } if (tty) { - tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno); + tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(fileno)); if (tmp == NULL) { PyErr_Clear(); tty = 0; @@ -2127,8 +2115,8 @@ builtin_input_impl(PyObject *module, PyObject *prompt) size_t len; /* stdin is a text stream, so it must have an encoding. */ - stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding); - stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors); + stdin_encoding = PyObject_GetAttr(fin, &_Py_ID(encoding)); + stdin_errors = PyObject_GetAttr(fin, &_Py_ID(errors)); if (!stdin_encoding || !stdin_errors || !PyUnicode_Check(stdin_encoding) || !PyUnicode_Check(stdin_errors)) { @@ -2139,7 +2127,7 @@ builtin_input_impl(PyObject *module, PyObject *prompt) stdin_errors_str = PyUnicode_AsUTF8(stdin_errors); if (!stdin_encoding_str || !stdin_errors_str) goto _readline_errors; - tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush); + tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush)); if (tmp == NULL) PyErr_Clear(); else @@ -2148,8 +2136,8 @@ builtin_input_impl(PyObject *module, PyObject *prompt) /* We have a prompt, encode it as stdout would */ const char *stdout_encoding_str, *stdout_errors_str; PyObject *stringpo; - stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding); - stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors); + stdout_encoding = PyObject_GetAttr(fout, &_Py_ID(encoding)); + stdout_errors = PyObject_GetAttr(fout, &_Py_ID(errors)); if (!stdout_encoding || !stdout_errors || !PyUnicode_Check(stdout_encoding) || !PyUnicode_Check(stdout_errors)) { @@ -2234,7 +2222,7 @@ builtin_input_impl(PyObject *module, PyObject *prompt) if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0) return NULL; } - tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush); + tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush)); if (tmp == NULL) PyErr_Clear(); else @@ -2285,7 +2273,7 @@ builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits) return NULL; } - round = _PyObject_LookupSpecial(number, &PyId___round__); + round = _PyObject_LookupSpecial(number, &_Py_ID(__round__)); if (round == NULL) { if (!PyErr_Occurred()) PyErr_Format(PyExc_TypeError, @@ -2346,7 +2334,7 @@ builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject if (newlist == NULL) return NULL; - callable = _PyObject_GetAttrId(newlist, &PyId_sort); + callable = PyObject_GetAttr(newlist, &_Py_ID(sort)); if (callable == NULL) { Py_DECREF(newlist); return NULL; @@ -2378,7 +2366,7 @@ builtin_vars(PyObject *self, PyObject *args) Py_XINCREF(d); } else { - if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) { + if (_PyObject_LookupAttr(v, &_Py_ID(__dict__), &d) == 0) { PyErr_SetString(PyExc_TypeError, "vars() argument must have __dict__ attribute"); } diff --git a/Python/ceval.c b/Python/ceval.c index dcceee5..02e4e7b 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -48,8 +48,6 @@ # error "ceval.c must be build with Py_BUILD_CORE define for best performance" #endif -_Py_IDENTIFIER(__name__); - /* Forward declarations */ static PyObject *trace_call_function( PyThreadState *tstate, PyObject *callable, PyObject **stack, @@ -864,18 +862,12 @@ match_keys(PyThreadState *tstate, PyObject *map, PyObject *keys) PyObject *seen = NULL; PyObject *dummy = NULL; PyObject *values = NULL; - PyObject *get_name = NULL; PyObject *get = NULL; // We use the two argument form of map.get(key, default) for two reasons: // - Atomically check for a key and get its value without error handling. // - Don't cause key creation or resizing in dict subclasses like // collections.defaultdict that define __missing__ (or similar). - _Py_IDENTIFIER(get); - get_name = _PyUnicode_FromId(&PyId_get); // borrowed - if (get_name == NULL) { - return NULL; - } - int meth_found = _PyObject_GetMethod(map, get_name, &get); + int meth_found = _PyObject_GetMethod(map, &_Py_ID(get), &get); if (get == NULL) { goto fail; } @@ -1692,9 +1684,8 @@ resume_frame: SET_LOCALS_FROM_FRAME(); #ifdef LLTRACE - _Py_IDENTIFIER(__ltrace__); { - int r = _PyDict_ContainsId(GLOBALS(), &PyId___ltrace__); + int r = PyDict_Contains(GLOBALS(), &_Py_ID(__ltrace__)); if (r < 0) { goto exit_unwind; } @@ -2330,9 +2321,8 @@ handle_eval_breaker: } TARGET(PRINT_EXPR) { - _Py_IDENTIFIER(displayhook); PyObject *value = POP(); - PyObject *hook = _PySys_GetObjectId(&PyId_displayhook); + PyObject *hook = _PySys_GetAttr(tstate, &_Py_ID(displayhook)); PyObject *res; if (hook == NULL) { _PyErr_SetString(tstate, PyExc_RuntimeError, @@ -2537,12 +2527,11 @@ handle_eval_breaker: if (tstate->c_tracefunc == NULL) { gen_status = PyIter_Send(receiver, v, &retval); } else { - _Py_IDENTIFIER(send); if (Py_IsNone(v) && PyIter_Check(receiver)) { retval = Py_TYPE(receiver)->tp_iternext(receiver); } else { - retval = _PyObject_CallMethodIdOneArg(receiver, &PyId_send, v); + retval = PyObject_CallMethodOneArg(receiver, &_Py_ID(send), v); } if (retval == NULL) { if (tstate->c_tracefunc != NULL @@ -2675,11 +2664,10 @@ handle_eval_breaker: } TARGET(LOAD_BUILD_CLASS) { - _Py_IDENTIFIER(__build_class__); - PyObject *bc; if (PyDict_CheckExact(BUILTINS())) { - bc = _PyDict_GetItemIdWithError(BUILTINS(), &PyId___build_class__); + bc = _PyDict_GetItemWithError(BUILTINS(), + &_Py_ID(__build_class__)); if (bc == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_SetString(tstate, PyExc_NameError, @@ -2690,10 +2678,7 @@ handle_eval_breaker: Py_INCREF(bc); } else { - PyObject *build_class_str = _PyUnicode_FromId(&PyId___build_class__); - if (build_class_str == NULL) - goto error; - bc = PyObject_GetItem(BUILTINS(), build_class_str); + bc = PyObject_GetItem(BUILTINS(), &_Py_ID(__build_class__)); if (bc == NULL) { if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) _PyErr_SetString(tstate, PyExc_NameError, @@ -3252,7 +3237,6 @@ handle_eval_breaker: } TARGET(SETUP_ANNOTATIONS) { - _Py_IDENTIFIER(__annotations__); int err; PyObject *ann_dict; if (LOCALS() == NULL) { @@ -3262,8 +3246,8 @@ handle_eval_breaker: } /* check if __annotations__ in locals()... */ if (PyDict_CheckExact(LOCALS())) { - ann_dict = _PyDict_GetItemIdWithError(LOCALS(), - &PyId___annotations__); + ann_dict = _PyDict_GetItemWithError(LOCALS(), + &_Py_ID(__annotations__)); if (ann_dict == NULL) { if (_PyErr_Occurred(tstate)) { goto error; @@ -3273,8 +3257,8 @@ handle_eval_breaker: if (ann_dict == NULL) { goto error; } - err = _PyDict_SetItemId(LOCALS(), - &PyId___annotations__, ann_dict); + err = PyDict_SetItem(LOCALS(), &_Py_ID(__annotations__), + ann_dict); Py_DECREF(ann_dict); if (err != 0) { goto error; @@ -3283,11 +3267,7 @@ handle_eval_breaker: } else { /* do the same if locals() is not a dict */ - PyObject *ann_str = _PyUnicode_FromId(&PyId___annotations__); - if (ann_str == NULL) { - goto error; - } - ann_dict = PyObject_GetItem(LOCALS(), ann_str); + ann_dict = PyObject_GetItem(LOCALS(), &_Py_ID(__annotations__)); if (ann_dict == NULL) { if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { goto error; @@ -3297,7 +3277,8 @@ handle_eval_breaker: if (ann_dict == NULL) { goto error; } - err = PyObject_SetItem(LOCALS(), ann_str, ann_dict); + err = PyObject_SetItem(LOCALS(), &_Py_ID(__annotations__), + ann_dict); Py_DECREF(ann_dict); if (err != 0) { goto error; @@ -4203,11 +4184,9 @@ handle_eval_breaker: } TARGET(BEFORE_ASYNC_WITH) { - _Py_IDENTIFIER(__aenter__); - _Py_IDENTIFIER(__aexit__); PyObject *mgr = TOP(); PyObject *res; - PyObject *enter = _PyObject_LookupSpecial(mgr, &PyId___aenter__); + PyObject *enter = _PyObject_LookupSpecial(mgr, &_Py_ID(__aenter__)); if (enter == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_Format(tstate, PyExc_TypeError, @@ -4217,7 +4196,7 @@ handle_eval_breaker: } goto error; } - PyObject *exit = _PyObject_LookupSpecial(mgr, &PyId___aexit__); + PyObject *exit = _PyObject_LookupSpecial(mgr, &_Py_ID(__aexit__)); if (exit == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_Format(tstate, PyExc_TypeError, @@ -4241,11 +4220,9 @@ handle_eval_breaker: } TARGET(BEFORE_WITH) { - _Py_IDENTIFIER(__enter__); - _Py_IDENTIFIER(__exit__); PyObject *mgr = TOP(); PyObject *res; - PyObject *enter = _PyObject_LookupSpecial(mgr, &PyId___enter__); + PyObject *enter = _PyObject_LookupSpecial(mgr, &_Py_ID(__enter__)); if (enter == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_Format(tstate, PyExc_TypeError, @@ -4255,7 +4232,7 @@ handle_eval_breaker: } goto error; } - PyObject *exit = _PyObject_LookupSpecial(mgr, &PyId___exit__); + PyObject *exit = _PyObject_LookupSpecial(mgr, &_Py_ID(__exit__)); if (exit == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_Format(tstate, PyExc_TypeError, @@ -6793,20 +6770,26 @@ PyEval_GetBuiltins(void) /* Convenience function to get a builtin from its name */ PyObject * -_PyEval_GetBuiltinId(_Py_Identifier *name) +_PyEval_GetBuiltin(PyObject *name) { PyThreadState *tstate = _PyThreadState_GET(); - PyObject *attr = _PyDict_GetItemIdWithError(PyEval_GetBuiltins(), name); + PyObject *attr = PyDict_GetItemWithError(PyEval_GetBuiltins(), name); if (attr) { Py_INCREF(attr); } else if (!_PyErr_Occurred(tstate)) { - _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(name)); + _PyErr_SetObject(tstate, PyExc_AttributeError, name); } return attr; } PyObject * +_PyEval_GetBuiltinId(_Py_Identifier *name) +{ + return _PyEval_GetBuiltin(_PyUnicode_FromId(name)); +} + +PyObject * PyEval_GetLocals(void) { PyThreadState *tstate = _PyThreadState_GET(); @@ -7047,11 +7030,10 @@ static PyObject * import_name(PyThreadState *tstate, InterpreterFrame *frame, PyObject *name, PyObject *fromlist, PyObject *level) { - _Py_IDENTIFIER(__import__); PyObject *import_func, *res; PyObject* stack[5]; - import_func = _PyDict_GetItemIdWithError(frame->f_builtins, &PyId___import__); + import_func = _PyDict_GetItemWithError(frame->f_builtins, &_Py_ID(__import__)); if (import_func == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found"); @@ -7098,7 +7080,7 @@ import_from(PyThreadState *tstate, PyObject *v, PyObject *name) /* Issue #17636: in case this failed because of a circular relative import, try to fallback on reading the module directly from sys.modules. */ - pkgname = _PyObject_GetAttrId(v, &PyId___name__); + pkgname = PyObject_GetAttr(v, &_Py_ID(__name__)); if (pkgname == NULL) { goto error; } @@ -7140,8 +7122,7 @@ import_from(PyThreadState *tstate, PyObject *v, PyObject *name) PyErr_SetImportError(errmsg, pkgname, NULL); } else { - _Py_IDENTIFIER(__spec__); - PyObject *spec = _PyObject_GetAttrId(v, &PyId___spec__); + PyObject *spec = PyObject_GetAttr(v, &_Py_ID(__spec__)); const char *fmt = _PyModuleSpec_IsInitializing(spec) ? "cannot import name %R from partially initialized module %R " @@ -7163,17 +7144,15 @@ import_from(PyThreadState *tstate, PyObject *v, PyObject *name) static int import_all_from(PyThreadState *tstate, PyObject *locals, PyObject *v) { - _Py_IDENTIFIER(__all__); - _Py_IDENTIFIER(__dict__); PyObject *all, *dict, *name, *value; int skip_leading_underscores = 0; int pos, err; - if (_PyObject_LookupAttrId(v, &PyId___all__, &all) < 0) { + if (_PyObject_LookupAttr(v, &_Py_ID(__all__), &all) < 0) { return -1; /* Unexpected error */ } if (all == NULL) { - if (_PyObject_LookupAttrId(v, &PyId___dict__, &dict) < 0) { + if (_PyObject_LookupAttr(v, &_Py_ID(__dict__), &dict) < 0) { return -1; } if (dict == NULL) { @@ -7200,7 +7179,7 @@ import_all_from(PyThreadState *tstate, PyObject *locals, PyObject *v) break; } if (!PyUnicode_Check(name)) { - PyObject *modname = _PyObject_GetAttrId(v, &PyId___name__); + PyObject *modname = PyObject_GetAttr(v, &_Py_ID(__name__)); if (modname == NULL) { Py_DECREF(name); err = -1; @@ -7400,14 +7379,13 @@ format_exc_check_arg(PyThreadState *tstate, PyObject *exc, if (exc == PyExc_NameError) { // Include the name in the NameError exceptions to offer suggestions later. - _Py_IDENTIFIER(name); PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); if (PyErr_GivenExceptionMatches(value, PyExc_NameError)) { // We do not care if this fails because we are going to restore the // NameError anyway. - (void)_PyObject_SetAttrId(value, &PyId_name, obj); + (void)PyObject_SetAttr(value, &_Py_ID(name), obj); } PyErr_Restore(type, value, traceback); } diff --git a/Python/codecs.c b/Python/codecs.c index 343b6e2..33965f8 100644 --- a/Python/codecs.c +++ b/Python/codecs.c @@ -522,7 +522,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; @@ -536,7 +535,7 @@ PyObject * _PyCodec_LookupTextEncoding(const char *encoding, * attribute. */ if (!PyTuple_CheckExact(codec)) { - if (_PyObject_LookupAttrId(codec, &PyId__is_text_encoding, &attr) < 0) { + if (_PyObject_LookupAttr(codec, &_Py_ID(_is_text_encoding), &attr) < 0) { Py_DECREF(codec); return NULL; } diff --git a/Python/compile.c b/Python/compile.c index 3f33f30..5f9bcf1 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -632,11 +632,9 @@ compiler_unit_free(struct compiler_unit *u) static int compiler_set_qualname(struct compiler *c) { - _Py_static_string(dot, "."); - _Py_static_string(dot_locals, ".<locals>"); Py_ssize_t stack_size; struct compiler_unit *u = c->u; - PyObject *name, *base, *dot_str, *dot_locals_str; + PyObject *name, *base; base = NULL; stack_size = PyList_GET_SIZE(c->c_stack); @@ -667,11 +665,10 @@ compiler_set_qualname(struct compiler *c) if (!force_global) { if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION - || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) { - dot_locals_str = _PyUnicode_FromId(&dot_locals); - if (dot_locals_str == NULL) - return 0; - base = PyUnicode_Concat(parent->u_qualname, dot_locals_str); + || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) + { + base = PyUnicode_Concat(parent->u_qualname, + &_Py_STR(dot_locals)); if (base == NULL) return 0; } @@ -683,12 +680,7 @@ compiler_set_qualname(struct compiler *c) } if (base != NULL) { - dot_str = _PyUnicode_FromId(&dot); - if (dot_str == NULL) { - Py_DECREF(base); - return 0; - } - name = PyUnicode_Concat(base, dot_str); + name = PyUnicode_Concat(base, &_Py_STR(dot)); Py_DECREF(base); if (name == NULL) return 0; @@ -1603,17 +1595,11 @@ 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); assert(PyDict_GET_SIZE(u->u_cellvars) == 0); - name = _PyUnicode_FromId(&PyId___class__); - if (!name) { - compiler_unit_free(u); - return 0; - } - res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero()); + res = PyDict_SetItem(u->u_cellvars, &_Py_ID(__class__), + _PyLong_GetZero()); if (res < 0) { compiler_unit_free(u); return 0; @@ -1998,11 +1984,6 @@ compiler_body(struct compiler *c, asdl_stmt_seq *stmts) int i = 0; stmt_ty st; PyObject *docstring; - _Py_IDENTIFIER(__doc__); - PyObject *__doc__ = _PyUnicode_FromId(&PyId___doc__); /* borrowed ref*/ - if (__doc__ == NULL) { - return 0; - } /* Set current line number to the line number of first statement. This way line number for SETUP_ANNOTATIONS will always @@ -2027,7 +2008,7 @@ compiler_body(struct compiler *c, asdl_stmt_seq *stmts) assert(st->kind == Expr_kind); VISIT(c, expr, st->v.Expr.value); UNSET_LOC(c); - if (!compiler_nameop(c, __doc__, Store)) + if (!compiler_nameop(c, &_Py_ID(__doc__), Store)) return 0; } } @@ -2041,12 +2022,8 @@ compiler_mod(struct compiler *c, mod_ty mod) { PyCodeObject *co; int addNone = 1; - _Py_static_string(PyId__module, "<module>"); - PyObject *module = _PyUnicode_FromId(&PyId__module); /* borrowed ref */ - if (module == NULL) { - return 0; - } - if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1)) { + if (!compiler_enter_scope(c, &_Py_STR(anon_module), COMPILER_SCOPE_MODULE, + mod, 1)) { return NULL; } c->u->u_lineno = 1; @@ -2324,7 +2301,6 @@ compiler_visit_annotations(struct compiler *c, arguments_ty args, Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed. */ - _Py_IDENTIFIER(return); Py_ssize_t annotations_len = 0; if (!compiler_visit_argannotations(c, args->args, &annotations_len)) @@ -2342,11 +2318,8 @@ compiler_visit_annotations(struct compiler *c, arguments_ty args, args->kwarg->annotation, &annotations_len)) return 0; - identifier return_str = _PyUnicode_FromId(&PyId_return); /* borrowed ref */ - if (return_str == NULL) { - return 0; - } - if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) { + if (!compiler_visit_argannotation(c, &_Py_ID(return), returns, + &annotations_len)) { return 0; } @@ -2891,7 +2864,6 @@ compiler_lambda(struct compiler *c, expr_ty e) { PyCodeObject *co; PyObject *qualname; - identifier name; Py_ssize_t funcflags; arguments_ty args = e->v.Lambda.args; assert(e->kind == Lambda_kind); @@ -2899,18 +2871,12 @@ compiler_lambda(struct compiler *c, expr_ty e) if (!compiler_check_debug_args(c, args)) return 0; - _Py_static_string(PyId_lambda, "<lambda>"); - name = _PyUnicode_FromId(&PyId_lambda); /* borrowed ref */ - if (name == NULL) { - return 0; - } - funcflags = compiler_default_arguments(c, args); if (funcflags == -1) { return 0; } - if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA, + if (!compiler_enter_scope(c, &_Py_STR(anon_lambda), COMPILER_SCOPE_LAMBDA, (void *)e, e->lineno)) { return 0; } @@ -3809,12 +3775,6 @@ compiler_from_import(struct compiler *c, stmt_ty s) { Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names); PyObject *names; - _Py_static_string(PyId_empty_string, ""); - PyObject *empty_string = _PyUnicode_FromId(&PyId_empty_string); /* borrowed ref */ - - if (empty_string == NULL) { - return 0; - } ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level)); @@ -3841,7 +3801,7 @@ compiler_from_import(struct compiler *c, stmt_ty s) ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); } else { - ADDOP_NAME(c, IMPORT_NAME, empty_string, names); + ADDOP_NAME(c, IMPORT_NAME, &_Py_STR(empty), names); } for (i = 0; i < n; i++) { alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); @@ -5389,13 +5349,8 @@ error: static int compiler_genexp(struct compiler *c, expr_ty e) { - _Py_static_string(PyId_genexpr, "<genexpr>"); - identifier name = _PyUnicode_FromId(&PyId_genexpr); /* borrowed ref */ - if (name == NULL) { - return 0; - } assert(e->kind == GeneratorExp_kind); - return compiler_comprehension(c, e, COMP_GENEXP, name, + return compiler_comprehension(c, e, COMP_GENEXP, &_Py_STR(anon_genexpr), e->v.GeneratorExp.generators, e->v.GeneratorExp.elt, NULL); } @@ -5403,13 +5358,8 @@ compiler_genexp(struct compiler *c, expr_ty e) static int compiler_listcomp(struct compiler *c, expr_ty e) { - _Py_static_string(PyId_listcomp, "<listcomp>"); - identifier name = _PyUnicode_FromId(&PyId_listcomp); /* borrowed ref */ - if (name == NULL) { - return 0; - } assert(e->kind == ListComp_kind); - return compiler_comprehension(c, e, COMP_LISTCOMP, name, + return compiler_comprehension(c, e, COMP_LISTCOMP, &_Py_STR(anon_listcomp), e->v.ListComp.generators, e->v.ListComp.elt, NULL); } @@ -5417,13 +5367,8 @@ compiler_listcomp(struct compiler *c, expr_ty e) static int compiler_setcomp(struct compiler *c, expr_ty e) { - _Py_static_string(PyId_setcomp, "<setcomp>"); - identifier name = _PyUnicode_FromId(&PyId_setcomp); /* borrowed ref */ - if (name == NULL) { - return 0; - } assert(e->kind == SetComp_kind); - return compiler_comprehension(c, e, COMP_SETCOMP, name, + return compiler_comprehension(c, e, COMP_SETCOMP, &_Py_STR(anon_setcomp), e->v.SetComp.generators, e->v.SetComp.elt, NULL); } @@ -5432,13 +5377,8 @@ compiler_setcomp(struct compiler *c, expr_ty e) static int compiler_dictcomp(struct compiler *c, expr_ty e) { - _Py_static_string(PyId_dictcomp, "<dictcomp>"); - identifier name = _PyUnicode_FromId(&PyId_dictcomp); /* borrowed ref */ - if (name == NULL) { - return 0; - } assert(e->kind == DictComp_kind); - return compiler_comprehension(c, e, COMP_DICTCOMP, name, + return compiler_comprehension(c, e, COMP_DICTCOMP, &_Py_STR(anon_dictcomp), e->v.DictComp.generators, e->v.DictComp.key, e->v.DictComp.value); } @@ -5960,12 +5900,6 @@ compiler_annassign(struct compiler *c, stmt_ty s) { expr_ty targ = s->v.AnnAssign.target; PyObject* mangled; - _Py_IDENTIFIER(__annotations__); - /* borrowed ref*/ - PyObject *__annotations__ = _PyUnicode_FromId(&PyId___annotations__); - if (__annotations__ == NULL) { - return 0; - } assert(s->kind == AnnAssign_kind); @@ -5988,7 +5922,7 @@ compiler_annassign(struct compiler *c, stmt_ty s) else { VISIT(c, expr, s->v.AnnAssign.annotation); } - ADDOP_NAME(c, LOAD_NAME, __annotations__, names); + ADDOP_NAME(c, LOAD_NAME, &_Py_ID(__annotations__), names); mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id); ADDOP_LOAD_CONST_NEW(c, mangled); ADDOP(c, STORE_SUBSCR); diff --git a/Python/errors.c b/Python/errors.c index 0232349..10a06a5 100644 --- a/Python/errors.c +++ b/Python/errors.c @@ -28,12 +28,6 @@ extern char *strerror(int); extern "C" { #endif -_Py_IDENTIFIER(__main__); -_Py_IDENTIFIER(__module__); -_Py_IDENTIFIER(builtins); -_Py_IDENTIFIER(stderr); -_Py_IDENTIFIER(flush); - /* Forward declarations */ static PyObject * _PyErr_FormatV(PyThreadState *tstate, PyObject *exception, @@ -1135,7 +1129,7 @@ PyErr_NewException(const char *name, PyObject *base, PyObject *dict) goto failure; } - int r = _PyDict_ContainsId(dict, &PyId___module__); + int r = PyDict_Contains(dict, &_Py_ID(__module__)); if (r < 0) { goto failure; } @@ -1144,7 +1138,7 @@ PyErr_NewException(const char *name, PyObject *base, PyObject *dict) (Py_ssize_t)(dot-name)); if (modulename == NULL) goto failure; - if (_PyDict_SetItemId(dict, &PyId___module__, modulename) != 0) + if (PyDict_SetItem(dict, &_Py_ID(__module__), modulename) != 0) goto failure; } if (PyTuple_Check(base)) { @@ -1347,7 +1341,7 @@ write_unraisable_exc_file(PyThreadState *tstate, PyObject *exc_type, assert(PyExceptionClass_Check(exc_type)); - PyObject *modulename = _PyObject_GetAttrId(exc_type, &PyId___module__); + PyObject *modulename = PyObject_GetAttr(exc_type, &_Py_ID(__module__)); if (modulename == NULL || !PyUnicode_Check(modulename)) { Py_XDECREF(modulename); _PyErr_Clear(tstate); @@ -1356,8 +1350,8 @@ write_unraisable_exc_file(PyThreadState *tstate, PyObject *exc_type, } } else { - if (!_PyUnicode_EqualToASCIIId(modulename, &PyId_builtins) && - !_PyUnicode_EqualToASCIIId(modulename, &PyId___main__)) { + if (!_PyUnicode_Equal(modulename, &_Py_ID(builtins)) && + !_PyUnicode_Equal(modulename, &_Py_ID(__main__))) { if (PyFile_WriteObject(modulename, file, Py_PRINT_RAW) < 0) { Py_DECREF(modulename); return -1; @@ -1405,7 +1399,7 @@ write_unraisable_exc_file(PyThreadState *tstate, PyObject *exc_type, } /* Explicitly call file.flush() */ - PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush); + PyObject *res = _PyObject_CallMethodNoArgs(file, &_Py_ID(flush)); if (!res) { return -1; } @@ -1420,7 +1414,7 @@ write_unraisable_exc(PyThreadState *tstate, PyObject *exc_type, PyObject *exc_value, PyObject *exc_tb, PyObject *err_msg, PyObject *obj) { - PyObject *file = _PySys_GetObjectId(&PyId_stderr); + PyObject *file = _PySys_GetAttr(tstate, &_Py_ID(stderr)); if (file == NULL || file == Py_None) { return 0; } @@ -1524,8 +1518,7 @@ _PyErr_WriteUnraisableMsg(const char *err_msg_str, PyObject *obj) goto error; } - _Py_IDENTIFIER(unraisablehook); - PyObject *hook = _PySys_GetObjectId(&PyId_unraisablehook); + PyObject *hook = _PySys_GetAttr(tstate, &_Py_ID(unraisablehook)); if (hook == NULL) { Py_DECREF(hook_args); goto default_hook; @@ -1600,14 +1593,6 @@ PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset, int end_lineno, int end_col_offset) { PyObject *exc, *v, *tb, *tmp; - _Py_IDENTIFIER(filename); - _Py_IDENTIFIER(lineno); - _Py_IDENTIFIER(end_lineno); - _Py_IDENTIFIER(msg); - _Py_IDENTIFIER(offset); - _Py_IDENTIFIER(end_offset); - _Py_IDENTIFIER(print_file_and_line); - _Py_IDENTIFIER(text); PyThreadState *tstate = _PyThreadState_GET(); /* add attributes for the line number and filename for the error */ @@ -1619,7 +1604,7 @@ PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset, if (tmp == NULL) _PyErr_Clear(tstate); else { - if (_PyObject_SetAttrId(v, &PyId_lineno, tmp)) { + if (PyObject_SetAttr(v, &_Py_ID(lineno), tmp)) { _PyErr_Clear(tstate); } Py_DECREF(tmp); @@ -1631,7 +1616,7 @@ PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset, _PyErr_Clear(tstate); } } - if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None)) { + if (PyObject_SetAttr(v, &_Py_ID(offset), tmp ? tmp : Py_None)) { _PyErr_Clear(tstate); } Py_XDECREF(tmp); @@ -1643,7 +1628,7 @@ PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset, _PyErr_Clear(tstate); } } - if (_PyObject_SetAttrId(v, &PyId_end_lineno, tmp ? tmp : Py_None)) { + if (PyObject_SetAttr(v, &_Py_ID(end_lineno), tmp ? tmp : Py_None)) { _PyErr_Clear(tstate); } Py_XDECREF(tmp); @@ -1655,20 +1640,20 @@ PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset, _PyErr_Clear(tstate); } } - if (_PyObject_SetAttrId(v, &PyId_end_offset, tmp ? tmp : Py_None)) { + if (PyObject_SetAttr(v, &_Py_ID(end_offset), tmp ? tmp : Py_None)) { _PyErr_Clear(tstate); } Py_XDECREF(tmp); tmp = NULL; if (filename != NULL) { - if (_PyObject_SetAttrId(v, &PyId_filename, filename)) { + if (PyObject_SetAttr(v, &_Py_ID(filename), filename)) { _PyErr_Clear(tstate); } tmp = PyErr_ProgramTextObject(filename, lineno); if (tmp) { - if (_PyObject_SetAttrId(v, &PyId_text, tmp)) { + if (PyObject_SetAttr(v, &_Py_ID(text), tmp)) { _PyErr_Clear(tstate); } Py_DECREF(tmp); @@ -1678,7 +1663,7 @@ PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset, } } if (exc != PyExc_SyntaxError) { - if (_PyObject_LookupAttrId(v, &PyId_msg, &tmp) < 0) { + if (_PyObject_LookupAttr(v, &_Py_ID(msg), &tmp) < 0) { _PyErr_Clear(tstate); } else if (tmp) { @@ -1687,7 +1672,7 @@ PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset, else { tmp = PyObject_Str(v); if (tmp) { - if (_PyObject_SetAttrId(v, &PyId_msg, tmp)) { + if (PyObject_SetAttr(v, &_Py_ID(msg), tmp)) { _PyErr_Clear(tstate); } Py_DECREF(tmp); @@ -1696,15 +1681,15 @@ PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset, _PyErr_Clear(tstate); } } - if (_PyObject_LookupAttrId(v, &PyId_print_file_and_line, &tmp) < 0) { + + if (_PyObject_LookupAttr(v, &_Py_ID(print_file_and_line), &tmp) < 0) { _PyErr_Clear(tstate); } else if (tmp) { Py_DECREF(tmp); } else { - if (_PyObject_SetAttrId(v, &PyId_print_file_and_line, - Py_None)) { + if (PyObject_SetAttr(v, &_Py_ID(print_file_and_line), Py_None)) { _PyErr_Clear(tstate); } } diff --git a/Python/import.c b/Python/import.c index 332db69..74f8e1d 100644 --- a/Python/import.c +++ b/Python/import.c @@ -36,9 +36,6 @@ extern struct _inittab _PyImport_Inittab[]; struct _inittab *PyImport_Inittab = _PyImport_Inittab; static struct _inittab *inittab_copy = NULL; -_Py_IDENTIFIER(__path__); -_Py_IDENTIFIER(__spec__); - /*[clinic input] module _imp [clinic start generated code]*/ @@ -74,9 +71,7 @@ _PyImportZip_Init(PyThreadState *tstate) } } else { - _Py_IDENTIFIER(zipimporter); - PyObject *zipimporter = _PyObject_GetAttrId(zipimport, - &PyId_zipimporter); + PyObject *zipimporter = PyObject_GetAttr(zipimport, &_Py_ID(zipimporter)); Py_DECREF(zipimport); if (zipimporter == NULL) { _PyErr_Clear(tstate); /* No zipimporter object -- okay */ @@ -345,20 +340,18 @@ import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *n { PyObject *spec; - _Py_IDENTIFIER(_lock_unlock_module); - /* Optimization: only call _bootstrap._lock_unlock_module() if __spec__._initializing is true. NOTE: because of this, initializing must be set *before* stuffing the new module in sys.modules. */ - spec = _PyObject_GetAttrId(mod, &PyId___spec__); + spec = PyObject_GetAttr(mod, &_Py_ID(__spec__)); int busy = _PyModuleSpec_IsInitializing(spec); Py_XDECREF(spec); if (busy) { /* Wait until module is done importing. */ - PyObject *value = _PyObject_CallMethodIdOneArg( - interp->importlib, &PyId__lock_unlock_module, name); + PyObject *value = _PyObject_CallMethodOneArg( + interp->importlib, &_Py_ID(_lock_unlock_module), name); if (value == NULL) { return -1; } @@ -710,7 +703,6 @@ PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, } else if (cpathobj != NULL) { PyInterpreterState *interp = _PyInterpreterState_GET(); - _Py_IDENTIFIER(_get_sourcefile); if (interp == NULL) { Py_FatalError("no current interpreter"); @@ -719,8 +711,8 @@ PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, external= PyObject_GetAttrString(interp->importlib, "_bootstrap_external"); if (external != NULL) { - pathobj = _PyObject_CallMethodIdOneArg( - external, &PyId__get_sourcefile, cpathobj); + pathobj = _PyObject_CallMethodOneArg( + external, &_Py_ID(_get_sourcefile), cpathobj); Py_DECREF(external); } if (pathobj == NULL) @@ -740,7 +732,6 @@ error: static PyObject * module_dict_for_exec(PyThreadState *tstate, PyObject *name) { - _Py_IDENTIFIER(__builtins__); PyObject *m, *d; m = import_add_module(tstate, name); @@ -749,10 +740,9 @@ module_dict_for_exec(PyThreadState *tstate, PyObject *name) /* If the module is being reloaded, we get the old module back and re-use its dict to exec the new code. */ d = PyModule_GetDict(m); - int r = _PyDict_ContainsId(d, &PyId___builtins__); + int r = PyDict_Contains(d, &_Py_ID(__builtins__)); if (r == 0) { - r = _PyDict_SetItemId(d, &PyId___builtins__, - PyEval_GetBuiltins()); + r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins()); } if (r < 0) { remove_module(tstate, name); @@ -794,7 +784,6 @@ PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, { PyThreadState *tstate = _PyThreadState_GET(); PyObject *d, *external, *res; - _Py_IDENTIFIER(_fix_up_module); d = module_dict_for_exec(tstate, name); if (d == NULL) { @@ -810,9 +799,8 @@ PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, Py_DECREF(d); return NULL; } - res = _PyObject_CallMethodIdObjArgs(external, - &PyId__fix_up_module, - d, name, pathname, cpathname, NULL); + res = PyObject_CallMethodObjArgs(external, &_Py_ID(_fix_up_module), + d, name, pathname, cpathname, NULL); Py_DECREF(external); if (res != NULL) { Py_DECREF(res); @@ -1542,9 +1530,6 @@ done: static PyObject * resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level) { - _Py_IDENTIFIER(__package__); - _Py_IDENTIFIER(__name__); - _Py_IDENTIFIER(parent); PyObject *abs_name; PyObject *package = NULL; PyObject *spec; @@ -1560,14 +1545,14 @@ resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict"); goto error; } - package = _PyDict_GetItemIdWithError(globals, &PyId___package__); + package = PyDict_GetItemWithError(globals, &_Py_ID(__package__)); if (package == Py_None) { package = NULL; } else if (package == NULL && _PyErr_Occurred(tstate)) { goto error; } - spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__); + spec = PyDict_GetItemWithError(globals, &_Py_ID(__spec__)); if (spec == NULL && _PyErr_Occurred(tstate)) { goto error; } @@ -1581,7 +1566,7 @@ resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level } else if (spec != NULL && spec != Py_None) { int equal; - PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent); + PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent)); if (parent == NULL) { goto error; } @@ -1600,7 +1585,7 @@ resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level } } else if (spec != NULL && spec != Py_None) { - package = _PyObject_GetAttrId(spec, &PyId_parent); + package = PyObject_GetAttr(spec, &_Py_ID(parent)); if (package == NULL) { goto error; } @@ -1617,7 +1602,7 @@ resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level goto error; } - package = _PyDict_GetItemIdWithError(globals, &PyId___name__); + package = PyDict_GetItemWithError(globals, &_Py_ID(__name__)); if (package == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_SetString(tstate, PyExc_KeyError, @@ -1633,7 +1618,7 @@ resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level goto error; } - int haspath = _PyDict_ContainsId(globals, &PyId___path__); + int haspath = PyDict_Contains(globals, &_Py_ID(__path__)); if (haspath < 0) { goto error; } @@ -1701,7 +1686,6 @@ resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level static PyObject * import_find_and_load(PyThreadState *tstate, PyObject *abs_name) { - _Py_IDENTIFIER(_find_and_load); PyObject *mod = NULL; PyInterpreterState *interp = tstate->interp; int import_time = _PyInterpreterState_GetConfig(interp)->import_time; @@ -1742,9 +1726,8 @@ import_find_and_load(PyThreadState *tstate, PyObject *abs_name) if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED()) PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name)); - mod = _PyObject_CallMethodIdObjArgs(interp->importlib, - &PyId__find_and_load, abs_name, - interp->import_func, NULL); + mod = PyObject_CallMethodObjArgs(interp->importlib, &_Py_ID(_find_and_load), + abs_name, interp->import_func, NULL); if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED()) PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name), @@ -1788,7 +1771,6 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, int level) { PyThreadState *tstate = _PyThreadState_GET(); - _Py_IDENTIFIER(_handle_fromlist); PyObject *abs_name = NULL; PyObject *final_mod = NULL; PyObject *mod = NULL; @@ -1909,13 +1891,13 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, } else { PyObject *path; - if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) { + if (_PyObject_LookupAttr(mod, &_Py_ID(__path__), &path) < 0) { goto error; } if (path) { Py_DECREF(path); - final_mod = _PyObject_CallMethodIdObjArgs( - interp->importlib, &PyId__handle_fromlist, + final_mod = PyObject_CallMethodObjArgs( + interp->importlib, &_Py_ID(_handle_fromlist), mod, fromlist, interp->import_func, NULL); } else { @@ -1955,10 +1937,8 @@ PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals PyObject * PyImport_ReloadModule(PyObject *m) { - _Py_IDENTIFIER(importlib); - _Py_IDENTIFIER(reload); PyObject *reloaded_module = NULL; - PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib); + PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib)); if (importlib == NULL) { if (PyErr_Occurred()) { return NULL; @@ -1970,7 +1950,7 @@ PyImport_ReloadModule(PyObject *m) } } - reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m); + reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m); Py_DECREF(importlib); return reloaded_module; } @@ -1988,26 +1968,12 @@ PyImport_ReloadModule(PyObject *m) PyObject * PyImport_Import(PyObject *module_name) { - _Py_IDENTIFIER(__import__); - _Py_IDENTIFIER(__builtins__); - PyThreadState *tstate = _PyThreadState_GET(); PyObject *globals = NULL; PyObject *import = NULL; PyObject *builtins = NULL; PyObject *r = NULL; - /* Initialize constant string objects */ - PyObject *import_str = _PyUnicode_FromId(&PyId___import__); // borrowed ref - if (import_str == NULL) { - return NULL; - } - - PyObject *builtins_str = _PyUnicode_FromId(&PyId___builtins__); // borrowed ref - if (builtins_str == NULL) { - return NULL; - } - PyObject *from_list = PyList_New(0); if (from_list == NULL) { goto err; @@ -2017,7 +1983,7 @@ PyImport_Import(PyObject *module_name) globals = PyEval_GetGlobals(); if (globals != NULL) { Py_INCREF(globals); - builtins = PyObject_GetItem(globals, builtins_str); + builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__)); if (builtins == NULL) goto err; } @@ -2028,20 +1994,20 @@ PyImport_Import(PyObject *module_name) if (builtins == NULL) { goto err; } - globals = Py_BuildValue("{OO}", builtins_str, builtins); + globals = Py_BuildValue("{OO}", &_Py_ID(__builtins__), builtins); if (globals == NULL) goto err; } /* Get the __import__ function from the builtins */ if (PyDict_Check(builtins)) { - import = PyObject_GetItem(builtins, import_str); + import = PyObject_GetItem(builtins, &_Py_ID(__import__)); if (import == NULL) { - _PyErr_SetObject(tstate, PyExc_KeyError, import_str); + _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__)); } } else - import = PyObject_GetAttr(builtins, import_str); + import = PyObject_GetAttr(builtins, &_Py_ID(__import__)); if (import == NULL) goto err; diff --git a/Python/importdl.c b/Python/importdl.c index 6d25547..f66c601 100644 --- a/Python/importdl.c +++ b/Python/importdl.c @@ -2,6 +2,9 @@ /* Support for dynamic loading of extension modules */ #include "Python.h" +#include "pycore_call.h" +#include "pycore_pystate.h" +#include "pycore_runtime.h" /* ./configure sets HAVE_DYNAMIC_LOADING if dynamic loading of modules is supported on this platform. configure will then compile and link in one @@ -38,7 +41,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); @@ -76,7 +78,7 @@ get_encoded_name(PyObject *name, const char **hook_prefix) { } /* Replace '-' by '_' */ - modname = _PyObject_CallMethodId(encoded, &PyId_replace, "cc", '-', '_'); + modname = _PyObject_CallMethod(encoded, &_Py_ID(replace), "cc", '-', '_'); if (modname == NULL) goto error; diff --git a/Python/marshal.c b/Python/marshal.c index 51c7755..44e4929 100644 --- a/Python/marshal.c +++ b/Python/marshal.c @@ -703,7 +703,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; @@ -713,7 +712,7 @@ r_string(Py_ssize_t n, RFILE *p) if (mview == NULL) return NULL; - res = _PyObject_CallMethodId(p->readable, &PyId_readinto, "N", mview); + res = _PyObject_CallMethod(p->readable, &_Py_ID(readinto), "N", mview); if (res != NULL) { read = PyNumber_AsSsize_t(res, PyExc_ValueError); Py_DECREF(res); @@ -1713,12 +1712,11 @@ 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) return NULL; - res = _PyObject_CallMethodIdOneArg(file, &PyId_write, s); + res = _PyObject_CallMethodOneArg(file, &_Py_ID(write), s); Py_DECREF(s); return res; } @@ -1745,7 +1743,6 @@ marshal_load(PyObject *module, PyObject *file) /*[clinic end generated code: output=f8e5c33233566344 input=c85c2b594cd8124a]*/ { PyObject *data, *result; - _Py_IDENTIFIER(read); RFILE rf; /* @@ -1755,7 +1752,7 @@ marshal_load(PyObject *module, PyObject *file) * This can be removed if we guarantee good error handling * for r_string() */ - data = _PyObject_CallMethodId(file, &PyId_read, "i", 0); + data = _PyObject_CallMethod(file, &_Py_ID(read), "i", 0); if (data == NULL) return NULL; if (!PyBytes_Check(data)) { diff --git a/Python/pylifecycle.c b/Python/pylifecycle.c index ba7bcd2..4a3a1ab 100644 --- a/Python/pylifecycle.c +++ b/Python/pylifecycle.c @@ -21,9 +21,9 @@ #include "pycore_pylifecycle.h" // _PyErr_Print() #include "pycore_pymem.h" // _PyObject_DebugMallocStats() #include "pycore_pystate.h" // _PyThreadState_GET() +#include "pycore_runtime.h" // _Py_ID() #include "pycore_runtime_init.h" // _PyRuntimeState_INIT #include "pycore_sliceobject.h" // _PySlice_Fini() -#include "pycore_structseq.h" // _PyStructSequence_InitState() #include "pycore_symtable.h" // _PySymtable_Fini() #include "pycore_sysmodule.h" // _PySys_ClearAuditHooks() #include "pycore_traceback.h" // _Py_DumpTracebackThreads() @@ -64,13 +64,6 @@ extern void _PyIO_Fini(void); #define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str)) -_Py_IDENTIFIER(flush); -_Py_IDENTIFIER(name); -_Py_IDENTIFIER(stdin); -_Py_IDENTIFIER(stdout); -_Py_IDENTIFIER(stderr); -_Py_IDENTIFIER(threading); - #ifdef __cplusplus extern "C" { #endif @@ -704,11 +697,6 @@ pycore_init_types(PyInterpreterState *interp) { PyStatus status; - status = _PyStructSequence_InitState(interp); - if (_PyStatus_EXCEPTION(status)) { - return status; - } - status = _PyTypes_InitState(interp); if (_PyStatus_EXCEPTION(status)) { return status; @@ -1450,8 +1438,7 @@ finalize_clear_modules_dict(PyObject *modules) PyDict_Clear(modules); } else { - _Py_IDENTIFIER(clear); - if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) { + if (PyObject_CallMethodNoArgs(modules, &_Py_ID(clear)) == NULL) { PyErr_WriteUnraisable(NULL); } } @@ -1622,13 +1609,14 @@ file_is_closed(PyObject *fobj) static int flush_std_files(void) { - PyObject *fout = _PySys_GetObjectId(&PyId_stdout); - PyObject *ferr = _PySys_GetObjectId(&PyId_stderr); + PyThreadState *tstate = _PyThreadState_GET(); + PyObject *fout = _PySys_GetAttr(tstate, &_Py_ID(stdout)); + PyObject *ferr = _PySys_GetAttr(tstate, &_Py_ID(stderr)); PyObject *tmp; int status = 0; if (fout != NULL && fout != Py_None && !file_is_closed(fout)) { - tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush); + tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush)); if (tmp == NULL) { PyErr_WriteUnraisable(fout); status = -1; @@ -1638,7 +1626,7 @@ flush_std_files(void) } if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) { - tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush); + tmp = PyObject_CallMethodNoArgs(ferr, &_Py_ID(flush)); if (tmp == NULL) { PyErr_Clear(); status = -1; @@ -2227,10 +2215,6 @@ create_stdio(const PyConfig *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)) @@ -2249,16 +2233,15 @@ create_stdio(const PyConfig *config, PyObject* io, mode = "wb"; else mode = "rb"; - buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO", - fd, mode, buffering, - Py_None, Py_None, /* encoding, errors */ - Py_None, Py_False); /* newline, closefd */ + buf = _PyObject_CallMethod(io, &_Py_ID(open), "isiOOOO", + fd, mode, buffering, + Py_None, Py_None, /* encoding, errors */ + Py_None, Py_False); /* newline, closefd */ if (buf == NULL) goto error; if (buffering) { - _Py_IDENTIFIER(raw); - raw = _PyObject_GetAttrId(buf, &PyId_raw); + raw = PyObject_GetAttr(buf, &_Py_ID(raw)); if (raw == NULL) goto error; } @@ -2274,9 +2257,9 @@ create_stdio(const PyConfig *config, PyObject* io, #endif text = PyUnicode_FromString(name); - if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0) + if (text == NULL || PyObject_SetAttr(raw, &_Py_ID(name), text) < 0) goto error; - res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty); + res = PyObject_CallMethodNoArgs(raw, &_Py_ID(isatty)); if (res == NULL) goto error; isatty = PyObject_IsTrue(res); @@ -2319,9 +2302,9 @@ create_stdio(const PyConfig *config, PyObject* io, goto error; } - stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO", - buf, encoding_str, errors_str, - newline, line_buffering, write_through); + stream = _PyObject_CallMethod(io, &_Py_ID(TextIOWrapper), "OOOsOO", + buf, encoding_str, errors_str, + newline, line_buffering, write_through); Py_CLEAR(buf); Py_CLEAR(encoding_str); Py_CLEAR(errors_str); @@ -2333,7 +2316,7 @@ create_stdio(const PyConfig *config, PyObject* io, else mode = "r"; text = PyUnicode_FromString(mode); - if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0) + if (!text || PyObject_SetAttr(stream, &_Py_ID(mode), text) < 0) goto error; Py_CLEAR(text); return stream; @@ -2432,7 +2415,7 @@ init_sys_streams(PyThreadState *tstate) if (std == NULL) goto error; PySys_SetObject("__stdin__", std); - _PySys_SetObjectId(&PyId_stdin, std); + _PySys_SetAttr(&_Py_ID(stdin), std); Py_DECREF(std); /* Set sys.stdout */ @@ -2443,7 +2426,7 @@ init_sys_streams(PyThreadState *tstate) if (std == NULL) goto error; PySys_SetObject("__stdout__", std); - _PySys_SetObjectId(&PyId_stdout, std); + _PySys_SetAttr(&_Py_ID(stdout), std); Py_DECREF(std); #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ @@ -2472,7 +2455,7 @@ init_sys_streams(PyThreadState *tstate) Py_DECREF(std); goto error; } - if (_PySys_SetObjectId(&PyId_stderr, std) < 0) { + if (_PySys_SetAttr(&_Py_ID(stderr), std) < 0) { Py_DECREF(std); goto error; } @@ -2522,7 +2505,7 @@ _Py_FatalError_PrintExc(PyThreadState *tstate) return 0; } - ferr = _PySys_GetObjectId(&PyId_stderr); + ferr = _PySys_GetAttr(tstate, &_Py_ID(stderr)); if (ferr == NULL || ferr == Py_None) { /* sys.stderr is not set yet or set to None, no need to try to display the exception */ @@ -2547,7 +2530,7 @@ _Py_FatalError_PrintExc(PyThreadState *tstate) Py_XDECREF(tb); /* sys.stderr may be buffered: call sys.stderr.flush() */ - res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush); + res = PyObject_CallMethodNoArgs(ferr, &_Py_ID(flush)); if (res == NULL) { _PyErr_Clear(tstate); } @@ -2899,9 +2882,8 @@ Py_ExitStatusException(PyStatus status) static void wait_for_thread_shutdown(PyThreadState *tstate) { - _Py_IDENTIFIER(_shutdown); PyObject *result; - PyObject *threading = _PyImport_GetModuleId(&PyId_threading); + PyObject *threading = PyImport_GetModule(&_Py_ID(threading)); if (threading == NULL) { if (_PyErr_Occurred(tstate)) { PyErr_WriteUnraisable(NULL); @@ -2909,7 +2891,7 @@ wait_for_thread_shutdown(PyThreadState *tstate) /* else: threading not imported */ return; } - result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown); + result = PyObject_CallMethodNoArgs(threading, &_Py_ID(_shutdown)); if (result == NULL) { PyErr_WriteUnraisable(threading); } diff --git a/Python/pythonrun.c b/Python/pythonrun.c index 6f170a4..b34a223 100644 --- a/Python/pythonrun.c +++ b/Python/pythonrun.c @@ -38,20 +38,6 @@ #endif -_Py_IDENTIFIER(__main__); -_Py_IDENTIFIER(builtins); -_Py_IDENTIFIER(excepthook); -_Py_IDENTIFIER(flush); -_Py_IDENTIFIER(last_traceback); -_Py_IDENTIFIER(last_type); -_Py_IDENTIFIER(last_value); -_Py_IDENTIFIER(ps1); -_Py_IDENTIFIER(ps2); -_Py_IDENTIFIER(stdin); -_Py_IDENTIFIER(stdout); -_Py_IDENTIFIER(stderr); -_Py_static_string(PyId_string, "<string>"); - #ifdef __cplusplus extern "C" { #endif @@ -130,14 +116,15 @@ _PyRun_InteractiveLoopObject(FILE *fp, PyObject *filename, PyCompilerFlags *flag flags = &local_flags; } - PyObject *v = _PySys_GetObjectId(&PyId_ps1); + PyThreadState *tstate = _PyThreadState_GET(); + PyObject *v = _PySys_GetAttr(tstate, &_Py_ID(ps1)); if (v == NULL) { - _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> ")); + _PySys_SetAttr(&_Py_ID(ps1), v = PyUnicode_FromString(">>> ")); Py_XDECREF(v); } - v = _PySys_GetObjectId(&PyId_ps2); + v = _PySys_GetAttr(tstate, &_Py_ID(ps2)); if (v == NULL) { - _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... ")); + _PySys_SetAttr(&_Py_ID(ps2), v = PyUnicode_FromString("... ")); Py_XDECREF(v); } @@ -199,31 +186,25 @@ static int PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename, PyCompilerFlags *flags) { - PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name; + PyObject *m, *d, *v, *w, *oenc = NULL; mod_ty mod; 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) { - return -1; - } + PyThreadState *tstate = _PyThreadState_GET(); if (fp == stdin) { /* Fetch encoding from sys.stdin if possible. */ - v = _PySys_GetObjectId(&PyId_stdin); + v = _PySys_GetAttr(tstate, &_Py_ID(stdin)); if (v && v != Py_None) { - oenc = _PyObject_GetAttrId(v, &PyId_encoding); + oenc = PyObject_GetAttr(v, &_Py_ID(encoding)); if (oenc) enc = PyUnicode_AsUTF8(oenc); if (!enc) PyErr_Clear(); } } - v = _PySys_GetObjectId(&PyId_ps1); + v = _PySys_GetAttr(tstate, &_Py_ID(ps1)); if (v != NULL) { v = PyObject_Str(v); if (v == NULL) @@ -236,7 +217,7 @@ PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename, } } } - w = _PySys_GetObjectId(&PyId_ps2); + w = _PySys_GetAttr(tstate, &_Py_ID(ps2)); if (w != NULL) { w = PyObject_Str(w); if (w == NULL) @@ -271,7 +252,7 @@ PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename, } return -1; } - m = PyImport_AddModuleObject(mod_name); + m = PyImport_AddModuleObject(&_Py_ID(__main__)); if (m == NULL) { _PyArena_Free(arena); return -1; @@ -520,37 +501,28 @@ parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, { Py_ssize_t hold; PyObject *v; - _Py_IDENTIFIER(msg); - _Py_IDENTIFIER(filename); - _Py_IDENTIFIER(lineno); - _Py_IDENTIFIER(offset); - _Py_IDENTIFIER(end_lineno); - _Py_IDENTIFIER(end_offset); - _Py_IDENTIFIER(text); *message = NULL; *filename = NULL; /* new style errors. `err' is an instance */ - *message = _PyObject_GetAttrId(err, &PyId_msg); + *message = PyObject_GetAttr(err, &_Py_ID(msg)); if (!*message) goto finally; - v = _PyObject_GetAttrId(err, &PyId_filename); + v = PyObject_GetAttr(err, &_Py_ID(filename)); if (!v) goto finally; if (v == Py_None) { Py_DECREF(v); - *filename = _PyUnicode_FromId(&PyId_string); - if (*filename == NULL) - goto finally; + *filename = &_Py_STR(anon_string); Py_INCREF(*filename); } else { *filename = v; } - v = _PyObject_GetAttrId(err, &PyId_lineno); + v = PyObject_GetAttr(err, &_Py_ID(lineno)); if (!v) goto finally; hold = PyLong_AsSsize_t(v); @@ -559,7 +531,7 @@ parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, goto finally; *lineno = hold; - v = _PyObject_GetAttrId(err, &PyId_offset); + v = PyObject_GetAttr(err, &_Py_ID(offset)); if (!v) goto finally; if (v == Py_None) { @@ -574,7 +546,7 @@ parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, } if (Py_TYPE(err) == (PyTypeObject*)PyExc_SyntaxError) { - v = _PyObject_GetAttrId(err, &PyId_end_lineno); + v = PyObject_GetAttr(err, &_Py_ID(end_lineno)); if (!v) { PyErr_Clear(); *end_lineno = *lineno; @@ -590,7 +562,7 @@ parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, *end_lineno = hold; } - v = _PyObject_GetAttrId(err, &PyId_end_offset); + v = PyObject_GetAttr(err, &_Py_ID(end_offset)); if (!v) { PyErr_Clear(); *end_offset = -1; @@ -611,7 +583,7 @@ parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, *end_offset = -1; } - v = _PyObject_GetAttrId(err, &PyId_text); + v = PyObject_GetAttr(err, &_Py_ID(text)); if (!v) goto finally; if (v == Py_None) { @@ -745,8 +717,7 @@ _Py_HandleSystemExit(int *exitcode_p) if (PyExceptionInstance_Check(value)) { /* The error code should be in the `code' attribute. */ - _Py_IDENTIFIER(code); - PyObject *code = _PyObject_GetAttrId(value, &PyId_code); + PyObject *code = PyObject_GetAttr(value, &_Py_ID(code)); if (code) { Py_DECREF(value); value = code; @@ -761,7 +732,8 @@ _Py_HandleSystemExit(int *exitcode_p) exitcode = (int)PyLong_AsLong(value); } else { - PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr); + PyThreadState *tstate = _PyThreadState_GET(); + PyObject *sys_stderr = _PySys_GetAttr(tstate, &_Py_ID(stderr)); /* We clear the exception here to avoid triggering the assertion * in PyObject_Str that ensures it won't silently lose exception * details. @@ -824,17 +796,17 @@ _PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars) /* Now we know v != NULL too */ if (set_sys_last_vars) { - if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) { + if (_PySys_SetAttr(&_Py_ID(last_type), exception) < 0) { _PyErr_Clear(tstate); } - if (_PySys_SetObjectId(&PyId_last_value, v) < 0) { + if (_PySys_SetAttr(&_Py_ID(last_value), v) < 0) { _PyErr_Clear(tstate); } - if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) { + if (_PySys_SetAttr(&_Py_ID(last_traceback), tb) < 0) { _PyErr_Clear(tstate); } } - hook = _PySys_GetObjectId(&PyId_excepthook); + hook = _PySys_GetAttr(tstate, &_Py_ID(excepthook)); if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None, exception, v, tb) < 0) { if (PyErr_ExceptionMatches(PyExc_RuntimeError)) { @@ -979,9 +951,8 @@ print_exception_file_and_line(struct exception_print_context *ctx, { PyObject *f = ctx->file; - _Py_IDENTIFIER(print_file_and_line); PyObject *tmp; - int res = _PyObject_LookupAttrId(*value_p, &PyId_print_file_and_line, &tmp); + int res = _PyObject_LookupAttr(*value_p, &_Py_ID(print_file_and_line), &tmp); if (res <= 0) { if (res < 0) { PyErr_Clear(); @@ -1051,14 +1022,12 @@ print_exception_message(struct exception_print_context *ctx, PyObject *type, { PyObject *f = ctx->file; - _Py_IDENTIFIER(__module__); - assert(PyExceptionClass_Check(type)); if (write_indented_margin(ctx, f) < 0) { return -1; } - PyObject *modulename = _PyObject_GetAttrId(type, &PyId___module__); + PyObject *modulename = PyObject_GetAttr(type, &_Py_ID(__module__)); if (modulename == NULL || !PyUnicode_Check(modulename)) { Py_XDECREF(modulename); PyErr_Clear(); @@ -1067,8 +1036,8 @@ print_exception_message(struct exception_print_context *ctx, PyObject *type, } } else { - if (!_PyUnicode_EqualToASCIIId(modulename, &PyId_builtins) && - !_PyUnicode_EqualToASCIIId(modulename, &PyId___main__)) + if (!_PyUnicode_Equal(modulename, &_Py_ID(builtins)) && + !_PyUnicode_Equal(modulename, &_Py_ID(__main__))) { int res = PyFile_WriteObject(modulename, f, Py_PRINT_RAW); Py_DECREF(modulename); @@ -1168,9 +1137,7 @@ print_exception_note(struct exception_print_context *ctx, PyObject *value) return 0; } - _Py_IDENTIFIER(__note__); - - PyObject *note = _PyObject_GetAttrId(value, &PyId___note__); + PyObject *note = PyObject_GetAttr(value, &_Py_ID(__note__)); if (note == NULL) { return -1; } @@ -1549,11 +1516,13 @@ _PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *t } if (print_exception_recursive(&ctx, value) < 0) { PyErr_Clear(); + _PyObject_Dump(value); + fprintf(stderr, "lost sys.stderr\n"); } Py_XDECREF(ctx.seen); /* Call file.flush() */ - PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush); + PyObject *res = _PyObject_CallMethodNoArgs(file, &_Py_ID(flush)); if (!res) { /* Silently ignore file.flush() error */ PyErr_Clear(); @@ -1566,7 +1535,8 @@ _PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *t void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) { - PyObject *file = _PySys_GetObjectId(&PyId_stderr); + PyThreadState *tstate = _PyThreadState_GET(); + PyObject *file = _PySys_GetAttr(tstate, &_Py_ID(stderr)); if (file == NULL) { _PyObject_Dump(value); fprintf(stderr, "lost sys.stderr\n"); @@ -1587,20 +1557,16 @@ PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *ret = NULL; mod_ty mod; PyArena *arena; - PyObject *filename; - - filename = _PyUnicode_FromId(&PyId_string); /* borrowed */ - if (filename == NULL) - return NULL; arena = _PyArena_New(); if (arena == NULL) return NULL; - mod = _PyParser_ASTFromString(str, filename, start, flags, arena); + mod = _PyParser_ASTFromString( + str, &_Py_STR(anon_string), start, flags, arena); if (mod != NULL) - ret = run_mod(mod, filename, globals, locals, flags, arena); + ret = run_mod(mod, &_Py_STR(anon_string), globals, locals, flags, arena); _PyArena_Free(arena); return ret; } @@ -1662,17 +1628,18 @@ flush_io(void) /* Save the current exception */ PyErr_Fetch(&type, &value, &traceback); - f = _PySys_GetObjectId(&PyId_stderr); + PyThreadState *tstate = _PyThreadState_GET(); + f = _PySys_GetAttr(tstate, &_Py_ID(stderr)); if (f != NULL) { - r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush); + r = _PyObject_CallMethodNoArgs(f, &_Py_ID(flush)); if (r) Py_DECREF(r); else PyErr_Clear(); } - f = _PySys_GetObjectId(&PyId_stdout); + f = _PySys_GetAttr(tstate, &_Py_ID(stdout)); if (f != NULL) { - r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush); + r = _PyObject_CallMethodNoArgs(f, &_Py_ID(flush)); if (r) Py_DECREF(r); else diff --git a/Python/specialize.c b/Python/specialize.c index b95bdf7..2175923 100644 --- a/Python/specialize.c +++ b/Python/specialize.c @@ -1,6 +1,7 @@ #include "Python.h" #include "pycore_code.h" #include "pycore_dict.h" +#include "pycore_global_strings.h" // _Py_ID() #include "pycore_long.h" #include "pycore_moduleobject.h" #include "pycore_object.h" @@ -596,8 +597,6 @@ specialize_module_load_attr( { PyModuleObject *m = (PyModuleObject *)owner; PyObject *value = NULL; - PyObject *getattr; - _Py_IDENTIFIER(__getattr__); assert((owner->ob_type->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0); PyDictObject *dict = (PyDictObject *)m->md_dict; if (dict == NULL) { @@ -608,13 +607,8 @@ specialize_module_load_attr( SPECIALIZATION_FAIL(opcode, SPEC_FAIL_NON_STRING_OR_SPLIT); return -1; } - getattr = _PyUnicode_FromId(&PyId___getattr__); /* borrowed */ - if (getattr == NULL) { - SPECIALIZATION_FAIL(opcode, SPEC_FAIL_OVERRIDDEN); - PyErr_Clear(); - return -1; - } - Py_ssize_t index = _PyDict_GetItemHint(dict, getattr, -1, &value); + Py_ssize_t index = _PyDict_GetItemHint(dict, &_Py_ID(__getattr__), -1, + &value); assert(index != DKIX_ERROR); if (index != DKIX_EMPTY) { SPECIALIZATION_FAIL(opcode, SPEC_FAIL_MODULE_ATTR_NOT_FOUND); @@ -1223,7 +1217,6 @@ binary_subscr_fail_kind(PyTypeObject *container_type, PyObject *sub) } #endif -_Py_IDENTIFIER(__getitem__); #define SIMPLE_FUNCTION 0 @@ -1268,7 +1261,7 @@ _Py_Specialize_BinarySubscr( goto success; } PyTypeObject *cls = Py_TYPE(container); - PyObject *descriptor = _PyType_LookupId(cls, &PyId___getitem__); + PyObject *descriptor = _PyType_Lookup(cls, &_Py_ID(__getitem__)); if (descriptor && Py_TYPE(descriptor) == &PyFunction_Type) { PyFunctionObject *func = (PyFunctionObject *)descriptor; PyCodeObject *code = (PyCodeObject *)func->func_code; @@ -1385,8 +1378,7 @@ _Py_Specialize_StoreSubscr(PyObject *container, PyObject *sub, _Py_CODEUNIT *ins } goto fail; } - _Py_IDENTIFIER(__setitem__); - PyObject *descriptor = _PyType_LookupId(container_type, &PyId___setitem__); + PyObject *descriptor = _PyType_Lookup(container_type, &_Py_ID(__setitem__)); if (descriptor && Py_TYPE(descriptor) == &PyFunction_Type) { PyFunctionObject *func = (PyFunctionObject *)descriptor; PyCodeObject *code = (PyCodeObject *)func->func_code; @@ -1474,7 +1466,6 @@ builtin_call_fail_kind(int ml_flags) #endif static PyMethodDescrObject *_list_append = NULL; -_Py_IDENTIFIER(append); static int specialize_method_descriptor( @@ -1486,7 +1477,8 @@ specialize_method_descriptor( return -1; } if (_list_append == NULL) { - _list_append = (PyMethodDescrObject *)_PyType_LookupId(&PyList_Type, &PyId_append); + _list_append = (PyMethodDescrObject *)_PyType_Lookup(&PyList_Type, + &_Py_ID(append)); } assert(_list_append != NULL); if (nargs == 2 && descr == _list_append) { diff --git a/Python/sysmodule.c b/Python/sysmodule.c index acb0378..57bf04d 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -55,17 +55,21 @@ module sys #include "clinic/sysmodule.c.h" -_Py_IDENTIFIER(_); -_Py_IDENTIFIER(__sizeof__); -_Py_IDENTIFIER(_xoptions); -_Py_IDENTIFIER(buffer); -_Py_IDENTIFIER(builtins); -_Py_IDENTIFIER(encoding); -_Py_IDENTIFIER(path); -_Py_IDENTIFIER(stdout); -_Py_IDENTIFIER(stderr); -_Py_IDENTIFIER(warnoptions); -_Py_IDENTIFIER(write); +PyObject * +_PySys_GetAttr(PyThreadState *tstate, PyObject *name) +{ + PyObject *sd = tstate->interp->sysdict; + if (sd == NULL) { + return NULL; + } + PyObject *exc_type, *exc_value, *exc_tb; + _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb); + /* XXX Suppress a new exception if it was raised and restore + * the old one. */ + PyObject *value = _PyDict_GetItemWithError(sd, name); + _PyErr_Restore(tstate, exc_type, exc_value, exc_tb); + return value; +} static PyObject * sys_get_object_id(PyThreadState *tstate, _Py_Identifier *key) @@ -147,6 +151,13 @@ _PySys_SetObjectId(_Py_Identifier *key, PyObject *v) return sys_set_object_id(interp, key, v); } +int +_PySys_SetAttr(PyObject *key, PyObject *v) +{ + PyInterpreterState *interp = _PyInterpreterState_GET(); + return sys_set_object(interp, key, v); +} + static int sys_set_object_str(PyInterpreterState *interp, const char *name, PyObject *v) { @@ -258,9 +269,8 @@ sys_audit_tstate(PyThreadState *ts, const char *event, /* Disallow tracing in hooks unless explicitly enabled */ PyThreadState_EnterTracing(ts); while ((hook = PyIter_Next(hooks)) != NULL) { - _Py_IDENTIFIER(__cantrace__); PyObject *o; - int canTrace = _PyObject_LookupAttrId(hook, &PyId___cantrace__, &o); + int canTrace = _PyObject_LookupAttr(hook, &_Py_ID(__cantrace__), &o); if (o) { canTrace = PyObject_IsTrue(o); Py_DECREF(o); @@ -631,7 +641,7 @@ sys_displayhook_unencodable(PyObject *outf, PyObject *o) const char *stdout_encoding_str; int ret; - stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding); + stdout_encoding = PyObject_GetAttr(outf, &_Py_ID(encoding)); if (stdout_encoding == NULL) goto error; stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding); @@ -648,12 +658,12 @@ sys_displayhook_unencodable(PyObject *outf, PyObject *o) if (encoded == NULL) goto error; - if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) { + if (_PyObject_LookupAttr(outf, &_Py_ID(buffer), &buffer) < 0) { Py_DECREF(encoded); goto error; } if (buffer) { - result = _PyObject_CallMethodIdOneArg(buffer, &PyId_write, encoded); + result = PyObject_CallMethodOneArg(buffer, &_Py_ID(write), encoded); Py_DECREF(buffer); Py_DECREF(encoded); if (result == NULL) @@ -699,7 +709,7 @@ sys_displayhook(PyObject *module, PyObject *o) static PyObject *newline = NULL; PyThreadState *tstate = _PyThreadState_GET(); - builtins = _PyImport_GetModuleId(&PyId_builtins); + builtins = PyImport_GetModule(&_Py_ID(builtins)); if (builtins == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_SetString(tstate, PyExc_RuntimeError, @@ -715,9 +725,9 @@ sys_displayhook(PyObject *module, PyObject *o) if (o == Py_None) { Py_RETURN_NONE; } - if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0) + if (PyObject_SetAttr(builtins, &_Py_ID(_), Py_None) != 0) return NULL; - outf = sys_get_object_id(tstate, &PyId_stdout); + outf = _PySys_GetAttr(tstate, &_Py_ID(stdout)); if (outf == NULL || outf == Py_None) { _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout"); return NULL; @@ -744,7 +754,7 @@ sys_displayhook(PyObject *module, PyObject *o) } if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0) return NULL; - if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0) + if (PyObject_SetAttr(builtins, &_Py_ID(_), o) != 0) return NULL; Py_RETURN_NONE; } @@ -1676,7 +1686,7 @@ _PySys_GetSizeOf(PyObject *o) return (size_t)-1; } - method = _PyObject_LookupSpecial(o, &PyId___sizeof__); + method = _PyObject_LookupSpecial(o, &_Py_ID(__sizeof__)); if (method == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_Format(tstate, PyExc_TypeError, @@ -2218,7 +2228,7 @@ _PySys_ReadPreinitXOptions(PyConfig *config) static PyObject * get_warnoptions(PyThreadState *tstate) { - PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions); + PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions)); if (warnoptions == NULL || !PyList_Check(warnoptions)) { /* PEP432 TODO: we can reach this if warnoptions is NULL in the main * interpreter config. When that happens, we need to properly set @@ -2234,7 +2244,7 @@ get_warnoptions(PyThreadState *tstate) if (warnoptions == NULL) { return NULL; } - if (sys_set_object_id(tstate->interp, &PyId_warnoptions, warnoptions)) { + if (sys_set_object(tstate->interp, &_Py_ID(warnoptions), warnoptions)) { Py_DECREF(warnoptions); return NULL; } @@ -2252,7 +2262,7 @@ PySys_ResetWarnOptions(void) return; } - PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions); + PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions)); if (warnoptions == NULL || !PyList_Check(warnoptions)) return; PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); @@ -2306,7 +2316,7 @@ int PySys_HasWarnOptions(void) { PyThreadState *tstate = _PyThreadState_GET(); - PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions); + PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions)); return (warnoptions != NULL && PyList_Check(warnoptions) && PyList_GET_SIZE(warnoptions) > 0); } @@ -2314,7 +2324,7 @@ PySys_HasWarnOptions(void) static PyObject * get_xoptions(PyThreadState *tstate) { - PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions); + PyObject *xoptions = _PySys_GetAttr(tstate, &_Py_ID(_xoptions)); if (xoptions == NULL || !PyDict_Check(xoptions)) { /* PEP432 TODO: we can reach this if xoptions is NULL in the main * interpreter config. When that happens, we need to properly set @@ -2330,7 +2340,7 @@ get_xoptions(PyThreadState *tstate) if (xoptions == NULL) { return NULL; } - if (sys_set_object_id(tstate->interp, &PyId__xoptions, xoptions)) { + if (sys_set_object(tstate->interp, &_Py_ID(_xoptions), xoptions)) { Py_DECREF(xoptions); return NULL; } @@ -3032,7 +3042,7 @@ _PySys_SetPreliminaryStderr(PyObject *sysdict) if (pstderr == NULL) { goto error; } - if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) { + if (PyDict_SetItem(sysdict, &_Py_ID(stderr), pstderr) < 0) { goto error; } if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) { @@ -3157,7 +3167,7 @@ PySys_SetPath(const wchar_t *path) if ((v = makepathobject(path, DELIM)) == NULL) Py_FatalError("can't create sys.path"); PyInterpreterState *interp = _PyInterpreterState_GET(); - if (sys_set_object_id(interp, &PyId_path, v) != 0) { + if (sys_set_object(interp, &_Py_ID(path), v) != 0) { Py_FatalError("can't assign sys.path"); } Py_DECREF(v); @@ -3214,7 +3224,7 @@ PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) Py_FatalError("can't compute path0 from argv"); } - PyObject *sys_path = sys_get_object_id(tstate, &PyId_path); + PyObject *sys_path = _PySys_GetAttr(tstate, &_Py_ID(path)); if (sys_path != NULL) { if (PyList_Insert(sys_path, 0, path0) < 0) { Py_DECREF(path0); @@ -3241,7 +3251,7 @@ sys_pyfile_write_unicode(PyObject *unicode, PyObject *file) if (file == NULL) return -1; assert(unicode != NULL); - PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode); + PyObject *result = _PyObject_CallMethodOneArg(file, &_Py_ID(write), unicode); if (result == NULL) { return -1; } @@ -3296,7 +3306,7 @@ sys_pyfile_write(const char *text, PyObject *file) */ static void -sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va) +sys_write(PyObject *key, FILE *fp, const char *format, va_list va) { PyObject *file; PyObject *error_type, *error_value, *error_traceback; @@ -3305,7 +3315,7 @@ sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va) PyThreadState *tstate = _PyThreadState_GET(); _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback); - file = sys_get_object_id(tstate, key); + file = _PySys_GetAttr(tstate, key); written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); if (sys_pyfile_write(buffer, file) != 0) { _PyErr_Clear(tstate); @@ -3325,7 +3335,7 @@ PySys_WriteStdout(const char *format, ...) va_list va; va_start(va, format); - sys_write(&PyId_stdout, stdout, format, va); + sys_write(&_Py_ID(stdout), stdout, format, va); va_end(va); } @@ -3335,12 +3345,12 @@ PySys_WriteStderr(const char *format, ...) va_list va; va_start(va, format); - sys_write(&PyId_stderr, stderr, format, va); + sys_write(&_Py_ID(stderr), stderr, format, va); va_end(va); } static void -sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va) +sys_format(PyObject *key, FILE *fp, const char *format, va_list va) { PyObject *file, *message; PyObject *error_type, *error_value, *error_traceback; @@ -3348,7 +3358,7 @@ sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va) PyThreadState *tstate = _PyThreadState_GET(); _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback); - file = sys_get_object_id(tstate, key); + file = _PySys_GetAttr(tstate, key); message = PyUnicode_FromFormatV(format, va); if (message != NULL) { if (sys_pyfile_write_unicode(message, file) != 0) { @@ -3368,7 +3378,7 @@ PySys_FormatStdout(const char *format, ...) va_list va; va_start(va, format); - sys_format(&PyId_stdout, stdout, format, va); + sys_format(&_Py_ID(stdout), stdout, format, va); va_end(va); } @@ -3378,6 +3388,6 @@ PySys_FormatStderr(const char *format, ...) va_list va; va_start(va, format); - sys_format(&PyId_stderr, stderr, format, va); + sys_format(&_Py_ID(stderr), stderr, format, va); va_end(va); } diff --git a/Python/traceback.c b/Python/traceback.c index 4d6cbaa..f2ae38e 100644 --- a/Python/traceback.c +++ b/Python/traceback.c @@ -6,6 +6,7 @@ #include "code.h" // PyCode_Addr2Line etc #include "frameobject.h" // PyFrame_GetBack() #include "pycore_ast.h" // asdl_seq_* +#include "pycore_call.h" // _PyObject_CallMethodFormat() #include "pycore_compile.h" // _PyAST_Optimize #include "pycore_fileutils.h" // _Py_BEGIN_SUPPRESS_IPH #include "pycore_frame.h" // _PyFrame_GetCode() @@ -32,11 +33,6 @@ /* Function from Parser/tokenizer.c */ extern char* _PyTokenizer_FindEncodingFilename(int, PyObject *); -_Py_IDENTIFIER(TextIOWrapper); -_Py_IDENTIFIER(close); -_Py_IDENTIFIER(open); -_Py_IDENTIFIER(path); - /*[clinic input] class TracebackType "PyTracebackObject *" "&PyTraceback_Type" [clinic start generated code]*/ @@ -317,6 +313,7 @@ _Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject * const char* filepath; Py_ssize_t len; PyObject* result; + PyObject *open = NULL; filebytes = PyUnicode_EncodeFSDefault(filename); if (filebytes == NULL) { @@ -333,11 +330,13 @@ _Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject * tail++; taillen = strlen(tail); - syspath = _PySys_GetObjectId(&PyId_path); + PyThreadState *tstate = _PyThreadState_GET(); + syspath = _PySys_GetAttr(tstate, &_Py_ID(path)); if (syspath == NULL || !PyList_Check(syspath)) goto error; npath = PyList_Size(syspath); + open = PyObject_GetAttr(io, &_Py_ID(open)); for (i = 0; i < npath; i++) { v = PyList_GetItem(syspath, i); if (v == NULL) { @@ -364,7 +363,7 @@ _Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject * namebuf[len++] = SEP; strcpy(namebuf+len, tail); - binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb"); + binary = _PyObject_CallMethodFormat(tstate, open, "ss", namebuf, "rb"); if (binary != NULL) { result = binary; goto finally; @@ -376,6 +375,7 @@ _Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject * error: result = NULL; finally: + Py_XDECREF(open); Py_DECREF(filebytes); return result; } @@ -448,10 +448,11 @@ display_source_line_with_margin(PyObject *f, PyObject *filename, int lineno, int } io = PyImport_ImportModule("io"); - if (io == NULL) + if (io == NULL) { return -1; - binary = _PyObject_CallMethodId(io, &PyId_open, "Os", filename, "rb"); + } + binary = _PyObject_CallMethod(io, &_Py_ID(open), "Os", filename, "rb"); if (binary == NULL) { PyErr_Clear(); @@ -480,14 +481,15 @@ display_source_line_with_margin(PyObject *f, PyObject *filename, int lineno, int PyMem_Free(found_encoding); return 0; } - fob = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "Os", binary, encoding); + fob = _PyObject_CallMethod(io, &_Py_ID(TextIOWrapper), + "Os", binary, encoding); Py_DECREF(io); PyMem_Free(found_encoding); if (fob == NULL) { PyErr_Clear(); - res = _PyObject_CallMethodIdNoArgs(binary, &PyId_close); + res = PyObject_CallMethodNoArgs(binary, &_Py_ID(close)); Py_DECREF(binary); if (res) Py_DECREF(res); @@ -506,7 +508,7 @@ display_source_line_with_margin(PyObject *f, PyObject *filename, int lineno, int break; } } - res = _PyObject_CallMethodIdNoArgs(fob, &PyId_close); + res = PyObject_CallMethodNoArgs(fob, &_Py_ID(close)); if (res) { Py_DECREF(res); } |