From 73360393df3bdab54fd8deb5a3dde4b3f363c6a0 Mon Sep 17 00:00:00 2001 From: rdb Date: Mon, 29 Jan 2024 17:35:41 +0100 Subject: [PATCH] Switch use of Py_INCREF to new Py_NewRef function This is more idiomatic, simplifies the code, makes it easier to port to eg. HPy later on, and makes it easier to use the limited ABI (where it can be optimized to a tail call) later on A polyfill is provided for compatibility with Python versions 3.8 and 3.9 --- direct/src/dcparser/dcClass_ext.cxx | 20 ++---- direct/src/dcparser/dcPacker_ext.cxx | 3 +- .../src/distributed/cConnectionRepository.cxx | 18 ++--- direct/src/interval/cInterval_ext.cxx | 3 +- direct/src/showbase/extend_frozen.c | 6 +- dtool/src/dtoolutil/filename_ext.cxx | 3 +- .../interfaceMakerPythonNative.cxx | 54 ++++++--------- dtool/src/interrogatedb/dtool_super_base.cxx | 8 +-- dtool/src/interrogatedb/py_compat.h | 22 ++++++ dtool/src/interrogatedb/py_panda.I | 21 ++---- dtool/src/interrogatedb/py_panda.cxx | 28 +++----- dtool/src/interrogatedb/py_panda.h | 2 +- dtool/src/interrogatedb/py_wrappers.cxx | 51 +++++--------- .../collide/collisionHandlerPhysical_ext.cxx | 3 +- .../src/display/pythonGraphicsWindowProc.cxx | 3 +- panda/src/event/asyncFuture_ext.cxx | 12 ++-- panda/src/event/pythonTask.I | 13 ++-- panda/src/event/pythonTask.cxx | 68 ++++++++----------- panda/src/express/datagram_ext.I | 4 +- panda/src/express/pointerToArray_ext.I | 50 +++----------- panda/src/gobj/geomVertexArrayData_ext.cxx | 10 +-- panda/src/gobj/pythonTexturePoolFilter.cxx | 4 +- panda/src/linmath/lvecBase2_ext_src.I | 10 +-- panda/src/linmath/lvecBase3_ext_src.I | 10 +-- panda/src/linmath/lvecBase4_ext_src.I | 10 +-- panda/src/ode/odeBody_ext.I | 3 +- panda/src/ode/odeBody_ext.cxx | 3 +- panda/src/ode/odeSpace_ext.cxx | 5 +- panda/src/ode/odeUtil_ext.cxx | 5 +- panda/src/pgraph/nodePathCollection_ext.cxx | 7 +- panda/src/pgraph/nodePath_ext.I | 12 ++-- panda/src/pgraph/nodePath_ext.cxx | 9 +-- panda/src/pgraph/pandaNode_ext.cxx | 13 ++-- panda/src/pgraph/pythonLoaderFileType.cxx | 6 +- panda/src/pgraph/renderState_ext.cxx | 12 ++-- panda/src/pgraph/transformState_ext.cxx | 12 ++-- panda/src/pipeline/pythonThread.cxx | 27 +++----- panda/src/pnmimage/pfmFile_ext.cxx | 8 +-- panda/src/pstatclient/pStatClient_ext.cxx | 2 +- panda/src/putil/bamReader_ext.cxx | 9 +-- panda/src/putil/paramPyObject.I | 6 +- panda/src/putil/pythonCallbackObject.cxx | 11 ++- panda/src/putil/typedWritable_ext.cxx | 7 +- pandatool/src/deploy-stub/android_log.c | 4 +- 44 files changed, 217 insertions(+), 380 deletions(-) diff --git a/direct/src/dcparser/dcClass_ext.cxx b/direct/src/dcparser/dcClass_ext.cxx index f66156a322..cf09a97d34 100644 --- a/direct/src/dcparser/dcClass_ext.cxx +++ b/direct/src/dcparser/dcClass_ext.cxx @@ -41,9 +41,7 @@ void Extension:: set_class_def(PyObject *class_def) { PythonClassDefsImpl *defs = do_get_defs(); - Py_XINCREF(class_def); - Py_XDECREF(defs->_class_def); - defs->_class_def = class_def; + Py_XSETREF(defs->_class_def, Py_XNewRef(class_def)); } /** @@ -53,13 +51,11 @@ set_class_def(PyObject *class_def) { PyObject *Extension:: get_class_def() const { if (!has_class_def()) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } PythonClassDefsImpl *defs = do_get_defs(); - Py_INCREF(defs->_class_def); - return defs->_class_def; + return Py_NewRef(defs->_class_def); } /** @@ -80,9 +76,7 @@ void Extension:: set_owner_class_def(PyObject *owner_class_def) { PythonClassDefsImpl *defs = do_get_defs(); - Py_XINCREF(owner_class_def); - Py_XDECREF(defs->_owner_class_def); - defs->_owner_class_def = owner_class_def; + Py_XSETREF(defs->_owner_class_def, Py_XNewRef(owner_class_def)); } /** @@ -92,13 +86,11 @@ set_owner_class_def(PyObject *owner_class_def) { PyObject *Extension:: get_owner_class_def() const { if (!has_owner_class_def()) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } PythonClassDefsImpl *defs = do_get_defs(); - Py_INCREF(defs->_owner_class_def); - return defs->_owner_class_def; + return Py_NewRef(defs->_owner_class_def); } /** diff --git a/direct/src/dcparser/dcPacker_ext.cxx b/direct/src/dcparser/dcPacker_ext.cxx index 3338ee6e88..276a2dd7f9 100644 --- a/direct/src/dcparser/dcPacker_ext.cxx +++ b/direct/src/dcparser/dcPacker_ext.cxx @@ -173,8 +173,7 @@ unpack_object() { switch (pack_type) { case PT_invalid: - object = Py_None; - Py_INCREF(object); + object = Py_NewRef(Py_None); _this->unpack_skip(); break; diff --git a/direct/src/distributed/cConnectionRepository.cxx b/direct/src/distributed/cConnectionRepository.cxx index fe384776bd..0eb40547ef 100644 --- a/direct/src/distributed/cConnectionRepository.cxx +++ b/direct/src/distributed/cConnectionRepository.cxx @@ -725,9 +725,9 @@ handle_update_field() { // while we call the update method--otherwise, the update method might // get into trouble if it tried to delete the object from the doId2do // map. - Py_INCREF(distobj); - invoke_extension(dclass).receive_update(distobj, _di); - Py_DECREF(distobj); + PyObject *distobj_ref = Py_NewRef(distobj); + invoke_extension(dclass).receive_update(distobj_ref, _di); + Py_DECREF(distobj_ref); if (PyErr_Occurred()) { #if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) @@ -802,12 +802,12 @@ handle_update_field_owner() { // raised while we call the update method--otherwise, the update // method might get into trouble if it tried to delete the object from // the doId2do map. - Py_INCREF(distobjOV); + PyObject *distobjOV_ref = Py_NewRef(distobjOV); // make a copy of the datagram iterator so that we can use the main // iterator for the non-owner update DatagramIterator _odi(_di); - invoke_extension(dclass).receive_update(distobjOV, _odi); - Py_DECREF(distobjOV); + invoke_extension(dclass).receive_update(distobjOV_ref, _odi); + Py_DECREF(distobjOV_ref); if (PyErr_Occurred()) { #if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) @@ -846,9 +846,9 @@ handle_update_field_owner() { // while we call the update method--otherwise, the update method might // get into trouble if it tried to delete the object from the doId2do // map. - Py_INCREF(distobj); - invoke_extension(dclass).receive_update(distobj, _di); - Py_DECREF(distobj); + PyObject *distobj_ref = Py_NewRef(distobj); + invoke_extension(dclass).receive_update(distobj_ref, _di); + Py_DECREF(distobj_ref); if (PyErr_Occurred()) { #if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) diff --git a/direct/src/interval/cInterval_ext.cxx b/direct/src/interval/cInterval_ext.cxx index 1225bae004..8d6aa74338 100644 --- a/direct/src/interval/cInterval_ext.cxx +++ b/direct/src/interval/cInterval_ext.cxx @@ -32,8 +32,7 @@ static PyObject *gen_next(PyObject *self) { if (ival->get_state() != CInterval::S_final) { // Try again next frame. - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } else { PyErr_SetNone(PyExc_StopIteration); diff --git a/direct/src/showbase/extend_frozen.c b/direct/src/showbase/extend_frozen.c index 1a562f8a63..2fc4fc7a6c 100644 --- a/direct/src/showbase/extend_frozen.c +++ b/direct/src/showbase/extend_frozen.c @@ -147,14 +147,12 @@ py_is_frozen_module(PyObject *self, PyObject *args) { i = 0; while (PyImport_FrozenModules[i].name != NULL) { if (strcmp(PyImport_FrozenModules[i].name, name) == 0) { - Py_INCREF(Py_True); - return Py_True; + Py_RETURN_TRUE; } ++i; } - Py_INCREF(Py_False); - return Py_False; + Py_RETURN_FALSE; } /* diff --git a/dtool/src/dtoolutil/filename_ext.cxx b/dtool/src/dtoolutil/filename_ext.cxx index 7feec66a75..cc67d9dd2e 100644 --- a/dtool/src/dtoolutil/filename_ext.cxx +++ b/dtool/src/dtoolutil/filename_ext.cxx @@ -134,8 +134,7 @@ PyObject *Extension:: scan_directory() const { vector_string contents; if (!_this->scan_directory(contents)) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } PyObject *result = PyList_New(contents.size()); diff --git a/dtool/src/interrogate/interfaceMakerPythonNative.cxx b/dtool/src/interrogate/interfaceMakerPythonNative.cxx index de730a2126..f9a2983b08 100644 --- a/dtool/src/interrogate/interfaceMakerPythonNative.cxx +++ b/dtool/src/interrogate/interfaceMakerPythonNative.cxx @@ -797,9 +797,7 @@ write_python_instance(ostream &out, int indent_level, const string &return_expr, indent(out, indent_level) << "if (" << return_expr << " == nullptr) {\n"; indent(out, indent_level) - << " Py_INCREF(Py_None);\n"; - indent(out, indent_level) - << " return Py_None;\n"; + << " return Py_NewRef(Py_None);\n"; indent(out, indent_level) << "} else {\n"; // Special exception if we are returning TypedWritable, which might @@ -1372,16 +1370,15 @@ write_sub_module(ostream &out, Object *obj) { class_ptr = "(PyObject *)" + class_ptr; - // Note: PyModule_AddObject steals a reference, so we have to call Py_INCREF - // for every but the first time we add it to the module. - if (obj->_itype.is_typedef()) { - out << " Py_INCREF(" << class_ptr << ");\n"; + // The first time we add something to a module, we use PyModule_AddObject, + // which steals a reference. This saves a call to Py_DECREF. + if (!obj->_itype.is_typedef()) { + out << " PyModule_AddObject(module, \"" << export_class_name << "\", " << class_ptr << ");\n"; + } else { + out << " PyModule_AddObjectRef(module, \"" << export_class_name << "\", " << class_ptr << ");\n"; } - - out << " PyModule_AddObject(module, \"" << export_class_name << "\", " << class_ptr << ");\n"; if (export_class_name != export_class_name2) { - out << " Py_INCREF(Dtool_Ptr_" << class_name << ");\n"; - out << " PyModule_AddObject(module, \"" << export_class_name2 << "\", " << class_ptr << ");\n"; + out << " PyModule_AddObjectRef(module, \"" << export_class_name2 << "\", " << class_ptr << ");\n"; } } @@ -2038,8 +2035,7 @@ write_module_class(ostream &out, Object *obj) { out << " }\n"; } - out << " Py_INCREF(Py_NotImplemented);\n"; - out << " return Py_NotImplemented;\n"; + out << " return Py_NewRef(Py_NotImplemented);\n"; out << "}\n\n"; } break; @@ -2508,8 +2504,7 @@ write_module_class(ostream &out, Object *obj) { // of raising an exception, if the this pointer doesn't match. This // is for things like __pow__, which Python likes to call on the // wrong-type objects. - out << " Py_INCREF(Py_NotImplemented);\n"; - out << " return Py_NotImplemented;\n"; + out << " return Py_NewRef(Py_NotImplemented);\n"; out << " }\n"; set one_param_remaps; @@ -2862,8 +2857,7 @@ write_module_class(ostream &out, Object *obj) { has_local_richcompare = true; } - out << " Py_INCREF(Py_NotImplemented);\n"; - out << " return Py_NotImplemented;\n"; + out << " return Py_NewRef(Py_NotImplemented);\n"; out << "}\n\n"; } @@ -6297,7 +6291,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, } if (TypeManager::is_pointer_to_PyObject(remap->_return_type->get_orig_type())) { - indent(out, indent_level) << "Py_XINCREF(return_value);\n"; + return_expr = "Py_XNewRef(return_value)"; } else { return_expr = manage_return_value(out, indent_level, remap, "return_value"); } @@ -6488,8 +6482,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, } } else if (return_flags & RF_self) { - indent(out, indent_level) << "Py_INCREF(self);\n"; - indent(out, indent_level) << "return self;\n"; + indent(out, indent_level) << "return Py_NewRef(self);\n"; } else if (return_flags & RF_richcompare_zero) { indent(out, indent_level) @@ -6497,8 +6490,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, } else if (return_flags & RF_pyobject) { if (return_expr.empty()) { - indent(out, indent_level) << "Py_INCREF(Py_None);\n"; - indent(out, indent_level) << "return Py_None;\n"; + indent(out, indent_level) << "return Py_NewRef(Py_None);\n"; } else if (return_flags & RF_preserve_null) { indent(out, indent_level) << "if (" << return_expr << " == nullptr) {\n"; @@ -6619,8 +6611,7 @@ error_return(ostream &out, int indent_level, int return_flags) { indent(out, indent_level) << "return -1;\n"; } else if (return_flags & RF_err_notimplemented) { - indent(out, indent_level) << "Py_INCREF(Py_NotImplemented);\n"; - indent(out, indent_level) << "return Py_NotImplemented;\n"; + indent(out, indent_level) << "return Py_NewRef(Py_NotImplemented);\n"; } else if (return_flags & RF_err_null) { indent(out, indent_level) << "return nullptr;\n"; @@ -6668,8 +6659,7 @@ error_bad_args_return(ostream &out, int indent_level, int return_flags, indent(out, indent_level) << "return -1;\n"; } else if (return_flags & RF_err_notimplemented) { - indent(out, indent_level) << "Py_INCREF(Py_NotImplemented);\n"; - indent(out, indent_level) << "return Py_NotImplemented;\n"; + indent(out, indent_level) << "return Py_NewRef(Py_NotImplemented);\n"; } else if (return_flags & RF_err_null) { indent(out, indent_level) << "return nullptr;\n"; @@ -6991,8 +6981,7 @@ write_getset(ostream &out, Object *obj, Property *property) { /*if (property->_has_function != NULL) { out << " if (!local_this->" << property->_has_function->_ifunc.get_name() << "(index)) {\n" - << " Py_INCREF(Py_None);\n" - << " return Py_None;\n" + << " return Py_NewRef(Py_None);\n" << " }\n"; }*/ @@ -7237,10 +7226,8 @@ write_getset(ostream &out, Object *obj, Property *property) { // We have to create an args tuple only to unpack it later, ugh. out << " PyObject *args = PyTuple_New(2);\n" - << " PyTuple_SET_ITEM(args, 0, key);\n" - << " PyTuple_SET_ITEM(args, 1, value);\n" - << " Py_INCREF(key);\n" - << " Py_INCREF(value);\n"; + << " PyTuple_SET_ITEM(args, 0, Py_NewRef(key));\n" + << " PyTuple_SET_ITEM(args, 1, Py_NewRef(value));\n"; string expected_params; if (!write_function_forset(out, remaps, 2, 2, @@ -7423,8 +7410,7 @@ write_getset(ostream &out, Object *obj, Property *property) { } else { out << " if (!" << cClassName << "::" << property->_has_function->_ifunc.get_name() << "()) {\n"; } - out << " Py_INCREF(Py_None);\n" - << " return Py_None;\n" + out << " return Py_NewRef(Py_None);\n" << " }\n"; } diff --git a/dtool/src/interrogatedb/dtool_super_base.cxx b/dtool/src/interrogatedb/dtool_super_base.cxx index 085830a211..0b7613617e 100644 --- a/dtool/src/interrogatedb/dtool_super_base.cxx +++ b/dtool/src/interrogatedb/dtool_super_base.cxx @@ -27,15 +27,13 @@ static PyMemberDef standard_type_members[] = { static PyObject *GetSuperBase(PyObject *self) { Dtool_PyTypedObject *super_base = Dtool_GetSuperBase(); - Py_XINCREF((PyTypeObject *)super_base); // order is important .. this is used for static functions - return (PyObject *)super_base; + return Py_XNewRef((PyObject *)&super_base->_PyType); }; static void Dtool_PyModuleClassInit_DTOOL_SUPER_BASE(PyObject *module) { if (module != nullptr) { Dtool_PyTypedObject *super_base = Dtool_GetSuperBase(); - Py_INCREF((PyTypeObject *)&super_base); - PyModule_AddObject(module, "DTOOL_SUPER_BASE", (PyObject *)&super_base); + PyModule_AddObjectRef(module, "DTOOL_SUPER_BASE", (PyObject *)&super_base->_PyType); } } @@ -152,7 +150,7 @@ Dtool_PyTypedObject *Dtool_GetSuperBase() { PyErr_SetString(PyExc_TypeError, "PyType_Ready(Dtool_DTOOL_SUPER_BASE)"); return nullptr; } - Py_INCREF((PyTypeObject *)&super_base_type); + Py_INCREF(&super_base_type._PyType); PyDict_SetItemString(super_base_type._PyType.tp_dict, "DtoolGetSuperBase", PyCFunction_New(&methods[0], (PyObject *)&super_base_type)); diff --git a/dtool/src/interrogatedb/py_compat.h b/dtool/src/interrogatedb/py_compat.h index 2a340ff060..0344bcd149 100644 --- a/dtool/src/interrogatedb/py_compat.h +++ b/dtool/src/interrogatedb/py_compat.h @@ -241,6 +241,28 @@ INLINE PyObject *PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObje } #endif +/* Python 3.10 */ + +#if PY_VERSION_HEX < 0x030A0000 +INLINE int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value) { + int ret = PyModule_AddObject(module, name, value); + if (ret == 0) { + Py_INCREF(value); + } + return ret; +} + +ALWAYS_INLINE PyObject *Py_NewRef(PyObject *obj) { + Py_INCREF(obj); + return obj; +} + +ALWAYS_INLINE PyObject *Py_XNewRef(PyObject *obj) { + Py_XINCREF(obj); + return obj; +} +#endif + /* Python 3.12 */ #if PY_VERSION_HEX < 0x030C0000 diff --git a/dtool/src/interrogatedb/py_panda.I b/dtool/src/interrogatedb/py_panda.I index 9434d64617..f3cb5a1d12 100644 --- a/dtool/src/interrogatedb/py_panda.I +++ b/dtool/src/interrogatedb/py_panda.I @@ -97,8 +97,7 @@ ALWAYS_INLINE void Dtool_Assign_PyObject(PyObject *&ptr, PyObject *value) { PyObject *prev_value = ptr; if (prev_value != value) { - Py_XINCREF(value); - ptr = value; + ptr = Py_XNewRef(value); Py_XDECREF(prev_value); } } @@ -246,8 +245,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(unsigned long long value) { ALWAYS_INLINE PyObject *Dtool_WrapValue(bool value) { PyObject *result = (value ? Py_True : Py_False); - Py_INCREF(result); - return result; + return Py_NewRef(result); } ALWAYS_INLINE PyObject *Dtool_WrapValue(double value) { @@ -256,8 +254,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(double value) { ALWAYS_INLINE PyObject *Dtool_WrapValue(const char *value) { if (value == nullptr) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } else { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromString(value); @@ -269,8 +266,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(const char *value) { ALWAYS_INLINE PyObject *Dtool_WrapValue(const wchar_t *value) { if (value == nullptr) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } else { return PyUnicode_FromWideChar(value, (Py_ssize_t)wcslen(value)); } @@ -290,8 +286,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::wstring &value) { ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::string *value) { if (value == nullptr) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } else { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromStringAndSize(value->data(), (Py_ssize_t)value->length()); @@ -303,8 +298,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::string *value) { ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::wstring *value) { if (value == nullptr) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } else { return PyUnicode_FromWideChar(value->data(), (Py_ssize_t)value->length()); } @@ -323,8 +317,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(wchar_t value) { } ALWAYS_INLINE PyObject *Dtool_WrapValue(std::nullptr_t) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } ALWAYS_INLINE PyObject *Dtool_WrapValue(PyObject *value) { diff --git a/dtool/src/interrogatedb/py_panda.cxx b/dtool/src/interrogatedb/py_panda.cxx index eeb3646234..888a25a7ae 100644 --- a/dtool/src/interrogatedb/py_panda.cxx +++ b/dtool/src/interrogatedb/py_panda.cxx @@ -273,8 +273,7 @@ PyObject *_Dtool_Return_None() { return Dtool_Raise_AssertionError(); } #endif - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } /** @@ -290,9 +289,7 @@ PyObject *Dtool_Return_Bool(bool value) { return Dtool_Raise_AssertionError(); } #endif - PyObject *result = (value ? Py_True : Py_False); - Py_INCREF(result); - return result; + return Py_NewRef(value ? Py_True : Py_False); } /** @@ -325,8 +322,7 @@ static PyObject *Dtool_EnumType_New(PyTypeObject *subtype, PyObject *args, PyObj } if (Py_TYPE(arg) == subtype) { - Py_INCREF(arg); - return arg; + return Py_NewRef(arg); } PyObject *value2member = PyDict_GetItemString(subtype->tp_dict, "_value2member_map_"); @@ -334,8 +330,7 @@ static PyObject *Dtool_EnumType_New(PyTypeObject *subtype, PyObject *args, PyObj PyObject *member = PyDict_GetItem(value2member, arg); if (member != nullptr) { - Py_INCREF(member); - return member; + return Py_NewRef(member); } PyObject *repr = PyObject_Repr(arg); @@ -418,12 +413,10 @@ PyTypeObject *Dtool_EnumType_Create(const char *name, PyObject *names, const cha value2member_map_sunder_str = PyString_InternFromString("_value2member_map_"); #endif PyObject *name_value_tuple = PyTuple_New(4); - PyTuple_SET_ITEM(name_value_tuple, 0, name_str); - PyTuple_SET_ITEM(name_value_tuple, 1, value_str); + PyTuple_SET_ITEM(name_value_tuple, 0, Py_NewRef(name_str)); + PyTuple_SET_ITEM(name_value_tuple, 1, Py_NewRef(value_str)); PyTuple_SET_ITEM(name_value_tuple, 2, name_sunder_str); PyTuple_SET_ITEM(name_value_tuple, 3, value_sunder_str); - Py_INCREF(name_str); - Py_INCREF(value_str); PyObject *slots_dict = PyDict_New(); PyDict_SetItemString(slots_dict, "__slots__", name_value_tuple); @@ -516,8 +509,7 @@ PyObject *DTool_CreatePyInstance(void *local_this, Dtool_PyTypedObject &in_class if (local_this == nullptr) { // This is actually a very common case, so let's allow this, but return // Py_None consistently. This eliminates code in the wrappers. - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } Dtool_PyInstDef *self = (Dtool_PyInstDef *)PyType_GenericAlloc(&in_classdef._PyType, 0); @@ -724,8 +716,7 @@ PyObject *Dtool_BorrowThisReference(PyObject *self, PyObject *args) { to->_is_const = from->_is_const; to->_ptr_to_object = from->_ptr_to_object; - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } return PyErr_Format(PyExc_TypeError, "types %s and %s do not match", @@ -755,8 +746,7 @@ Dtool_AddToDictionary(PyObject *self1, PyObject *args) { if (PyErr_Occurred()) { return nullptr; } - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } /** diff --git a/dtool/src/interrogatedb/py_panda.h b/dtool/src/interrogatedb/py_panda.h index 726eeef9c9..1acfd17d74 100644 --- a/dtool/src/interrogatedb/py_panda.h +++ b/dtool/src/interrogatedb/py_panda.h @@ -237,7 +237,7 @@ EXPCL_PYPANDA PyObject *Dtool_Return_Bool(bool value); EXPCL_PYPANDA PyObject *_Dtool_Return(PyObject *value); #ifdef NDEBUG -#define Dtool_Return_None() (LIKELY(PyErr_Occurred() == nullptr) ? (Py_INCREF(Py_None), Py_None) : nullptr) +#define Dtool_Return_None() (LIKELY(PyErr_Occurred() == nullptr) ? (Py_NewRef(Py_None)) : nullptr) #define Dtool_Return(value) (LIKELY(PyErr_Occurred() == nullptr) ? value : nullptr) #else #define Dtool_Return_None() _Dtool_Return_None() diff --git a/dtool/src/interrogatedb/py_wrappers.cxx b/dtool/src/interrogatedb/py_wrappers.cxx index 0f41600de9..f0be01a3fb 100644 --- a/dtool/src/interrogatedb/py_wrappers.cxx +++ b/dtool/src/interrogatedb/py_wrappers.cxx @@ -243,8 +243,7 @@ static PyObject *Dtool_MutableSequenceWrapper_clear(PyObject *self, PyObject *) return nullptr; } } - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } /** @@ -270,8 +269,7 @@ static PyObject *Dtool_MutableSequenceWrapper_remove(PyObject *self, PyObject *v int cmp = PyObject_RichCompareBool(item, value, Py_EQ); if (cmp > 0) { if (wrap->_setitem_func(wrap->_base._self, index, nullptr) == 0) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } else { return nullptr; } @@ -405,8 +403,7 @@ static PyObject *Dtool_MutableSequenceWrapper_extend(PyObject *self, PyObject *a } Py_DECREF(iter); - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } /** @@ -481,8 +478,7 @@ static PyObject *Dtool_MappingWrapper_get(PyObject *self, PyObject *args) { return value; } else if (PyErr_ExceptionMatches(PyExc_KeyError)) { PyErr_Clear(); - Py_INCREF(defvalue); - return defvalue; + return Py_NewRef(defvalue); } else { return nullptr; } @@ -604,8 +600,7 @@ static PyObject *Dtool_MappingWrapper_keys(PyObject *self, PyObject *) { } (void)PyObject_INIT(keys, &wrapper_type); - Py_XINCREF(wrap->_base._self); - keys->_base._self = wrap->_base._self; + keys->_base._self = Py_XNewRef(wrap->_base._self); keys->_base._name = wrap->_base._name; keys->_keys._len_func = wrap->_keys._len_func; keys->_keys._getitem_func = wrap->_keys._getitem_func; @@ -745,8 +740,7 @@ static PyObject *Dtool_MappingWrapper_values(PyObject *self, PyObject *) { } (void)PyObject_INIT(values, &wrapper_type); - Py_XINCREF(wrap->_base._self); - values->_base._self = wrap->_base._self; + values->_base._self = Py_XNewRef(wrap->_base._self); values->_base._name = wrap->_base._name; values->_keys._len_func = wrap->_keys._len_func; values->_keys._getitem_func = wrap->_keys._getitem_func; @@ -894,8 +888,7 @@ static PyObject *Dtool_MappingWrapper_items(PyObject *self, PyObject *) { } (void)PyObject_INIT(items, &wrapper_type); - Py_XINCREF(wrap->_base._self); - items->_base._self = wrap->_base._self; + items->_base._self = Py_XNewRef(wrap->_base._self); items->_base._name = wrap->_base._name; items->_keys._len_func = wrap->_keys._len_func; items->_keys._getitem_func = wrap->_keys._getitem_func; @@ -945,8 +938,7 @@ static PyObject *Dtool_MutableMappingWrapper_pop(PyObject *self, PyObject *args) } } else if (PyErr_ExceptionMatches(PyExc_KeyError)) { PyErr_Clear(); - Py_INCREF(defvalue); - return defvalue; + return Py_NewRef(defvalue); } else { return nullptr; } @@ -1014,8 +1006,7 @@ static PyObject *Dtool_MutableMappingWrapper_clear(PyObject *self, PyObject *) { } } } - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } /** @@ -1046,8 +1037,7 @@ static PyObject *Dtool_MutableMappingWrapper_setdefault(PyObject *self, PyObject } else if (PyErr_ExceptionMatches(PyExc_KeyError)) { PyErr_Clear(); if (wrap->_setitem_func(wrap->_base._self, key, defvalue) == 0) { - Py_INCREF(defvalue); - return defvalue; + return Py_NewRef(defvalue); } } return nullptr; @@ -1071,8 +1061,7 @@ static PyObject *Dtool_MutableMappingWrapper_update(PyObject *self, PyObject *ar case 0: if (kwargs == nullptr) { // This is legal. - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } dict = kwargs; break; @@ -1093,8 +1082,7 @@ static PyObject *Dtool_MutableMappingWrapper_update(PyObject *self, PyObject *ar return nullptr; } } - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } /** @@ -1276,8 +1264,7 @@ Dtool_SequenceWrapper *Dtool_NewSequenceWrapper(PyObject *self, const char *name } (void)PyObject_INIT(wrap, &wrapper_type); - Py_XINCREF(self); - wrap->_base._self = self; + wrap->_base._self = Py_XNewRef(self); wrap->_base._name = name; wrap->_len_func = nullptr; wrap->_getitem_func = nullptr; @@ -1387,8 +1374,7 @@ Dtool_MutableSequenceWrapper *Dtool_NewMutableSequenceWrapper(PyObject *self, co } (void)PyObject_INIT(wrap, &wrapper_type); - Py_XINCREF(self); - wrap->_base._self = self; + wrap->_base._self = Py_XNewRef(self); wrap->_base._name = name; wrap->_len_func = nullptr; wrap->_getitem_func = nullptr; @@ -1502,8 +1488,7 @@ Dtool_MappingWrapper *Dtool_NewMappingWrapper(PyObject *self, const char *name) } (void)PyObject_INIT(wrap, &wrapper_type); - Py_XINCREF(self); - wrap->_base._self = self; + wrap->_base._self = Py_XNewRef(self); wrap->_base._name = name; wrap->_keys._len_func = nullptr; wrap->_keys._getitem_func = nullptr; @@ -1622,8 +1607,7 @@ Dtool_MappingWrapper *Dtool_NewMutableMappingWrapper(PyObject *self, const char } (void)PyObject_INIT(wrap, &wrapper_type); - Py_XINCREF(self); - wrap->_base._self = self; + wrap->_base._self = Py_XNewRef(self); wrap->_base._name = name; wrap->_keys._len_func = nullptr; wrap->_keys._getitem_func = nullptr; @@ -1700,8 +1684,7 @@ Dtool_NewGenerator(PyObject *self, iternextfunc gen_next) { Dtool_GeneratorWrapper *gen; gen = (Dtool_GeneratorWrapper *)PyType_GenericAlloc(&wrapper_type, 0); if (gen != nullptr) { - Py_INCREF(self); - gen->_base._self = self; + gen->_base._self = Py_NewRef(self); gen->_iternext_func = gen_next; } return (PyObject *)gen; diff --git a/panda/src/collide/collisionHandlerPhysical_ext.cxx b/panda/src/collide/collisionHandlerPhysical_ext.cxx index 023d7ba718..4fec83a6aa 100644 --- a/panda/src/collide/collisionHandlerPhysical_ext.cxx +++ b/panda/src/collide/collisionHandlerPhysical_ext.cxx @@ -32,8 +32,7 @@ __reduce__(PyObject *self) const { PyTuple_SET_ITEM(nodepaths, i++, DTool_CreatePyInstance((void *)center, Dtool_NodePath, false, true)); } else { - PyTuple_SET_ITEM(nodepaths, i++, Py_None); - Py_INCREF(Py_None); + PyTuple_SET_ITEM(nodepaths, i++, Py_NewRef(Py_None)); } CollisionHandlerPhysical::Colliders::const_iterator it; diff --git a/panda/src/display/pythonGraphicsWindowProc.cxx b/panda/src/display/pythonGraphicsWindowProc.cxx index fe2013bed1..53e7885697 100644 --- a/panda/src/display/pythonGraphicsWindowProc.cxx +++ b/panda/src/display/pythonGraphicsWindowProc.cxx @@ -26,8 +26,7 @@ PythonGraphicsWindowProc:: PythonGraphicsWindowProc(PyObject* function, PyObject* name) : PythonCallbackObject(function) { - _name = name; - Py_INCREF(_name); + _name = Py_NewRef(name); } /** diff --git a/panda/src/event/asyncFuture_ext.cxx b/panda/src/event/asyncFuture_ext.cxx index eaed216bfe..846bfa71b9 100644 --- a/panda/src/event/asyncFuture_ext.cxx +++ b/panda/src/event/asyncFuture_ext.cxx @@ -84,8 +84,7 @@ static PyObject *get_done_result(const AsyncFuture *future) { future->get_result(ptr, ref_ptr); if (ptr == nullptr) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } TypeHandle type = ptr->get_type(); @@ -141,9 +140,9 @@ static PyObject *gen_next(PyObject *self) { if (!future->done()) { // Continue awaiting the result. - Py_INCREF(self); - return self; - } else { + return Py_NewRef(self); + } + else { PyObject *result = get_done_result(future); if (result != nullptr) { PyErr_SetObject(PyExc_StopIteration, result); @@ -323,8 +322,7 @@ add_done_callback(PyObject *self, PyObject *fn) { _this->add_waiting_task(task); - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } /** diff --git a/panda/src/event/pythonTask.I b/panda/src/event/pythonTask.I index 78f8e30cc7..2e9bca8c64 100644 --- a/panda/src/event/pythonTask.I +++ b/panda/src/event/pythonTask.I @@ -16,8 +16,7 @@ */ INLINE PyObject *PythonTask:: get_function() { - Py_INCREF(_function); - return _function; + return Py_NewRef(_function); } /** @@ -25,8 +24,7 @@ get_function() { */ INLINE PyObject *PythonTask:: get_upon_death() { - Py_INCREF(_upon_death); - return _upon_death; + return Py_NewRef(_upon_death); } /** @@ -34,8 +32,7 @@ get_upon_death() { */ INLINE PyObject *PythonTask:: get_owner() const { - Py_INCREF(_owner); - return _owner; + return Py_NewRef(_owner); } /** @@ -50,7 +47,5 @@ set_result(PyObject *result) { nassertv(is_alive()); nassertv(!done()); nassertv(_exception == nullptr); - Py_INCREF(result); - Py_XDECREF(_exc_value); - _exc_value = result; + Py_XSETREF(_exc_value, Py_NewRef(result)); } diff --git a/panda/src/event/pythonTask.cxx b/panda/src/event/pythonTask.cxx index 2241ded5a7..6ea95be752 100644 --- a/panda/src/event/pythonTask.cxx +++ b/panda/src/event/pythonTask.cxx @@ -51,17 +51,17 @@ PythonTask(PyObject *func_or_coro, const std::string &name) : nassertv(func_or_coro != nullptr); if (func_or_coro == Py_None || PyCallable_Check(func_or_coro)) { - _function = func_or_coro; - Py_INCREF(_function); - } else if (PyCoro_CheckExact(func_or_coro)) { + _function = Py_NewRef(func_or_coro); + } + else if (PyCoro_CheckExact(func_or_coro)) { // We also allow passing in a coroutine, because why not. - _generator = func_or_coro; - Py_INCREF(_generator); - } else if (PyGen_CheckExact(func_or_coro)) { + _generator = Py_NewRef(func_or_coro); + } + else if (PyGen_CheckExact(func_or_coro)) { // Something emulating a coroutine. - _generator = func_or_coro; - Py_INCREF(_generator); - } else { + _generator = Py_NewRef(func_or_coro); + } + else { nassert_raise("Invalid function passed to PythonTask"); } @@ -114,10 +114,8 @@ PythonTask:: */ void PythonTask:: set_function(PyObject *function) { - Py_XDECREF(_function); + Py_XSETREF(_function, Py_NewRef(function)); - _function = function; - Py_INCREF(_function); if (_function != Py_None && !PyCallable_Check(_function)) { nassert_raise("Invalid function passed to PythonTask"); } @@ -165,18 +163,16 @@ get_args() { PyObject *with_task = PyTuple_New(num_args + 1); for (int i = 0; i < num_args; ++i) { PyObject *item = PyTuple_GET_ITEM(_args, i); - Py_INCREF(item); - PyTuple_SET_ITEM(with_task, i, item); + PyTuple_SET_ITEM(with_task, i, Py_NewRef(item)); } this->ref(); PyObject *self = DTool_CreatePyInstance(this, Dtool_PythonTask, true, false); PyTuple_SET_ITEM(with_task, num_args, self); return with_task; - - } else { - Py_INCREF(_args); - return _args; + } + else { + return Py_NewRef(_args); } } @@ -186,10 +182,8 @@ get_args() { */ void PythonTask:: set_upon_death(PyObject *upon_death) { - Py_XDECREF(_upon_death); + Py_XSETREF(_upon_death, Py_NewRef(upon_death)); - _upon_death = upon_death; - Py_INCREF(_upon_death); if (_upon_death != Py_None && !PyCallable_Check(_upon_death)) { nassert_raise("Invalid upon_death function passed to PythonTask"); } @@ -234,9 +228,7 @@ set_owner(PyObject *owner) { unregister_from_owner(); } - Py_XDECREF(_owner); - _owner = owner; - Py_INCREF(_owner); + Py_XSETREF(_owner, Py_NewRef(owner)); if (_owner != Py_None && _state != S_inactive) { register_to_owner(); @@ -254,14 +246,11 @@ get_result() const { if (_exception == nullptr) { // The result of the call is stored in _exc_value. - Py_XINCREF(_exc_value); - return _exc_value; - } else { + return Py_XNewRef(_exc_value); + } + else { _retrieved_exception = true; - Py_INCREF(_exception); - Py_XINCREF(_exc_value); - Py_XINCREF(_exc_traceback); - PyErr_Restore(_exception, _exc_value, _exc_traceback); + PyErr_Restore(Py_NewRef(_exception), Py_XNewRef(_exc_value), Py_XNewRef(_exc_traceback)); return nullptr; } } @@ -273,13 +262,15 @@ get_result() const { /*PyObject *PythonTask:: exception() const { if (_exception == nullptr) { - Py_INCREF(Py_None); - return Py_None; - } else if (_exc_value == nullptr || _exc_value == Py_None) { + return Py_NewRef(Py_None); + } + else if (_exc_value == nullptr || _exc_value == Py_None) { return PyObject_CallNoArgs(_exception); - } else if (PyTuple_Check(_exc_value)) { + } + else if (PyTuple_Check(_exc_value)) { return PyObject_Call(_exception, _exc_value, nullptr); - } else { + } + else { return PyObject_CallOneArg(_exception, _exc_value); } }*/ @@ -362,8 +353,7 @@ __getattribute__(PyObject *self, PyObject *attr) const { if (item != nullptr) { // PyDict_GetItem returns a borrowed reference. - Py_INCREF(item); - return item; + return Py_NewRef(item); } return PyObject_GenericGetAttr(self, attr); @@ -624,7 +614,7 @@ do_python_task() { if (result == nullptr) { result = Py_None; } - Py_INCREF(result); + result = Py_NewRef(result); Py_DECREF(exc); #else if (_PyGen_FetchStopIterationValue(&result) == 0) { diff --git a/panda/src/express/datagram_ext.I b/panda/src/express/datagram_ext.I index 284d9b2bf3..70a71a8b44 100644 --- a/panda/src/express/datagram_ext.I +++ b/panda/src/express/datagram_ext.I @@ -47,10 +47,10 @@ __reduce__() const { } extern struct Dtool_PyTypedObject Dtool_Datagram; - Py_INCREF((PyObject *)&Dtool_Datagram._PyType); + PyObject *tp = (PyObject *)&Dtool_Datagram._PyType; PyObject *result = PyTuple_New(2); - PyTuple_SET_ITEM(result, 0, (PyObject *)&Dtool_Datagram._PyType); + PyTuple_SET_ITEM(result, 0, Py_NewRef(tp)); PyTuple_SET_ITEM(result, 1, args); return result; } diff --git a/panda/src/express/pointerToArray_ext.I b/panda/src/express/pointerToArray_ext.I index 039f3f011c..3406a67263 100644 --- a/panda/src/express/pointerToArray_ext.I +++ b/panda/src/express/pointerToArray_ext.I @@ -304,10 +304,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { return -1; } - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); view->len = this->_this->size() * sizeof(Element); view->readonly = 0; @@ -345,10 +342,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { template<> INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); set_matrix_view(*view, flags, this->_this->size(), 3, false, false); @@ -367,10 +361,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { template<> INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); set_matrix_view(*view, flags, this->_this->size(), 3, true, false); @@ -389,10 +380,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { template<> INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); set_matrix_view(*view, flags, this->_this->size(), 4, false, false); @@ -411,10 +399,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { template<> INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); set_matrix_view(*view, flags, this->_this->size(), 4, true, false); @@ -473,10 +458,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { return -1; } - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); view->len = this->_this->size() * sizeof(Element); view->readonly = 1; @@ -518,10 +500,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { "Object is not writable."); return -1; } - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); set_matrix_view(*view, flags, this->_this->size(), 3, false, true); @@ -544,10 +523,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { "Object is not writable."); return -1; } - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); set_matrix_view(*view, flags, this->_this->size(), 3, true, true); @@ -570,10 +546,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { "Object is not writable."); return -1; } - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); set_matrix_view(*view, flags, this->_this->size(), 4, false, true); @@ -596,10 +569,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { "Object is not writable."); return -1; } - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) this->_this->p(); set_matrix_view(*view, flags, this->_this->size(), 4, true, true); diff --git a/panda/src/gobj/geomVertexArrayData_ext.cxx b/panda/src/gobj/geomVertexArrayData_ext.cxx index bc135cd184..d3ffa6704a 100644 --- a/panda/src/gobj/geomVertexArrayData_ext.cxx +++ b/panda/src/gobj/geomVertexArrayData_ext.cxx @@ -53,10 +53,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { view->internal = (void*) data; - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) handle->get_write_pointer(); view->len = row_size * handle->get_num_rows(); view->readonly = 0; @@ -115,10 +112,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { view->internal = (void*) data; - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void*) handle->get_read_pointer(true); view->len = row_size * handle->get_num_rows(); view->readonly = 1; diff --git a/panda/src/gobj/pythonTexturePoolFilter.cxx b/panda/src/gobj/pythonTexturePoolFilter.cxx index 0ceb5c0729..0fc11b181d 100644 --- a/panda/src/gobj/pythonTexturePoolFilter.cxx +++ b/panda/src/gobj/pythonTexturePoolFilter.cxx @@ -78,9 +78,7 @@ init(PyObject *tex_filter) { return false; } - _entry_point = tex_filter; - - Py_INCREF(_entry_point); + _entry_point = Py_NewRef(tex_filter); return true; } diff --git a/panda/src/linmath/lvecBase2_ext_src.I b/panda/src/linmath/lvecBase2_ext_src.I index 5b36e339ec..d435399721 100644 --- a/panda/src/linmath/lvecBase2_ext_src.I +++ b/panda/src/linmath/lvecBase2_ext_src.I @@ -265,8 +265,7 @@ __ifloordiv__(PyObject *self, FLOATTYPE scalar) { _this->_v(0) = std::floor(_this->_v(0) / scalar); _this->_v(1) = std::floor(_this->_v(1) / scalar); #endif - Py_INCREF(self); - return self; + return Py_NewRef(self); } /** @@ -295,8 +294,7 @@ INLINE_LINMATH PyObject *Extension:: __ipow__(PyObject *self, FLOATTYPE exponent) { _this->_v(0) = cpow(_this->_v(0), exponent); _this->_v(1) = cpow(_this->_v(1), exponent); - Py_INCREF(self); - return self; + return Py_NewRef(self); } /** @@ -371,10 +369,8 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { static const char format[2] = {FLOATTOKEN, 0}; static const Py_ssize_t shape = FLOATNAME(LVecBase2)::num_components; - Py_INCREF(self); - view->buf = (void *)_this->get_data(); - view->obj = self; + view->obj = Py_NewRef(self); view->len = 2 * sizeof(FLOATTYPE); view->readonly = 1; view->itemsize = sizeof(FLOATTYPE); diff --git a/panda/src/linmath/lvecBase3_ext_src.I b/panda/src/linmath/lvecBase3_ext_src.I index c59add2465..e69e0f00de 100644 --- a/panda/src/linmath/lvecBase3_ext_src.I +++ b/panda/src/linmath/lvecBase3_ext_src.I @@ -274,8 +274,7 @@ __ifloordiv__(PyObject *self, FLOATTYPE scalar) { _this->_v(1) = std::floor(_this->_v(1) / scalar); _this->_v(2) = std::floor(_this->_v(2) / scalar); #endif - Py_INCREF(self); - return self; + return Py_NewRef(self); } /** @@ -306,8 +305,7 @@ __ipow__(PyObject *self, FLOATTYPE exponent) { _this->_v(0) = cpow(_this->_v(0), exponent); _this->_v(1) = cpow(_this->_v(1), exponent); _this->_v(2) = cpow(_this->_v(2), exponent); - Py_INCREF(self); - return self; + return Py_NewRef(self); } /** @@ -384,10 +382,8 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { static const char format[2] = {FLOATTOKEN, 0}; static const Py_ssize_t shape = FLOATNAME(LVecBase3)::num_components; - Py_INCREF(self); - view->buf = (void *)_this->get_data(); - view->obj = self; + view->obj = Py_NewRef(self); view->len = 3 * sizeof(FLOATTYPE); view->readonly = 1; view->itemsize = sizeof(FLOATTYPE); diff --git a/panda/src/linmath/lvecBase4_ext_src.I b/panda/src/linmath/lvecBase4_ext_src.I index d1be8a5316..44c97033d7 100644 --- a/panda/src/linmath/lvecBase4_ext_src.I +++ b/panda/src/linmath/lvecBase4_ext_src.I @@ -287,8 +287,7 @@ __ifloordiv__(PyObject *self, FLOATTYPE scalar) { _this->_v(2) = std::floor(_this->_v(2) / scalar); _this->_v(3) = std::floor(_this->_v(3) / scalar); #endif - Py_INCREF(self); - return self; + return Py_NewRef(self); } /** @@ -321,8 +320,7 @@ __ipow__(PyObject *self, FLOATTYPE exponent) { _this->_v(1) = cpow(_this->_v(1), exponent); _this->_v(2) = cpow(_this->_v(2), exponent); _this->_v(3) = cpow(_this->_v(3), exponent); - Py_INCREF(self); - return self; + return Py_NewRef(self); } /** @@ -402,10 +400,8 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { static const char format[2] = {FLOATTOKEN, 0}; static const Py_ssize_t shape = FLOATNAME(LVecBase4)::num_components; - Py_INCREF(self); - view->buf = (void *)_this->get_data(); - view->obj = self; + view->obj = Py_NewRef(self); view->len = 4 * sizeof(FLOATTYPE); view->readonly = 1; view->itemsize = sizeof(FLOATTYPE); diff --git a/panda/src/ode/odeBody_ext.I b/panda/src/ode/odeBody_ext.I index 5535b900dd..340ea5e259 100644 --- a/panda/src/ode/odeBody_ext.I +++ b/panda/src/ode/odeBody_ext.I @@ -22,8 +22,7 @@ get_data() const { if (data == nullptr) { data = Py_None; } - Py_INCREF(data); - return data; + return Py_NewRef(data); } /** diff --git a/panda/src/ode/odeBody_ext.cxx b/panda/src/ode/odeBody_ext.cxx index 59361c5fa1..94892a55dd 100644 --- a/panda/src/ode/odeBody_ext.cxx +++ b/panda/src/ode/odeBody_ext.cxx @@ -25,8 +25,7 @@ set_data(PyObject *data) { void *old_data = _this->get_data(); if (data != nullptr && data != Py_None) { - Py_INCREF(data); - _this->set_data((void *)data); + _this->set_data((void *)Py_NewRef(data)); _this->_destroy_callback = &destroy_callback; } else { _this->set_data(nullptr); diff --git a/panda/src/ode/odeSpace_ext.cxx b/panda/src/ode/odeSpace_ext.cxx index 97e841f30b..4c6fb56161 100644 --- a/panda/src/ode/odeSpace_ext.cxx +++ b/panda/src/ode/odeSpace_ext.cxx @@ -82,10 +82,9 @@ collide(PyObject* arg, PyObject* callback) { return -1; } else { - _python_callback = (PyObject*) callback; - Py_XINCREF(_python_callback); + _python_callback = Py_NewRef(callback); dSpaceCollide(_this->get_id(), (void*) arg, &near_callback); - Py_XDECREF(_python_callback); + Py_CLEAR(_python_callback); return 0; } } diff --git a/panda/src/ode/odeUtil_ext.cxx b/panda/src/ode/odeUtil_ext.cxx index c5aabaa812..e3115bfda6 100644 --- a/panda/src/ode/odeUtil_ext.cxx +++ b/panda/src/ode/odeUtil_ext.cxx @@ -31,10 +31,9 @@ collide2(const OdeGeom &geom1, const OdeGeom &geom2, PyObject* arg, PyObject* ca PyErr_Format(PyExc_TypeError, "'%s' object is not callable", callback->ob_type->tp_name); return -1; } else { - _python_callback = (PyObject*) callback; - Py_XINCREF(_python_callback); + _python_callback = Py_XNewRef(callback); dSpaceCollide2(geom1.get_id(), geom2.get_id(), (void*) arg, &near_callback); - Py_XDECREF(_python_callback); + Py_CLEAR(_python_callback); return 0; } } diff --git a/panda/src/pgraph/nodePathCollection_ext.cxx b/panda/src/pgraph/nodePathCollection_ext.cxx index 836e2959e0..a06caf8380 100644 --- a/panda/src/pgraph/nodePathCollection_ext.cxx +++ b/panda/src/pgraph/nodePathCollection_ext.cxx @@ -110,10 +110,9 @@ get_tight_bounds() const { PyObject *max_inst = DTool_CreatePyInstance((void*) max_point, Dtool_LPoint3f, true, false); #endif return Py_BuildValue("NN", min_inst, max_inst); - - } else { - Py_INCREF(Py_None); - return Py_None; + } + else { + return Py_NewRef(Py_None); } } diff --git a/panda/src/pgraph/nodePath_ext.I b/panda/src/pgraph/nodePath_ext.I index 01554fb08d..0c919da368 100644 --- a/panda/src/pgraph/nodePath_ext.I +++ b/panda/src/pgraph/nodePath_ext.I @@ -23,8 +23,7 @@ INLINE PyObject *Extension:: get_python_tags() { // An empty NodePath returns None if (_this->is_empty()) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } return invoke_extension(_this->node()).get_python_tags(); } @@ -38,8 +37,7 @@ INLINE PyObject *Extension:: get_tag_keys() const { // An empty NodePath returns None if (_this->is_empty()) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } return invoke_extension(_this->node()).get_tag_keys(); } @@ -52,8 +50,7 @@ INLINE PyObject *Extension:: get_python_tag_keys() const { // An empty NodePath returns None if (_this->is_empty()) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } return invoke_extension(_this->node()).get_python_tag_keys(); } @@ -83,8 +80,7 @@ get_python_tag(PyObject *key) const { // An empty NodePath quietly returns no tags. This makes // get_net_python_tag() easier to implement. if (_this->is_empty()) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } return invoke_extension(_this->node()).get_python_tag(key); } diff --git a/panda/src/pgraph/nodePath_ext.cxx b/panda/src/pgraph/nodePath_ext.cxx index 3bcad4b423..23cfb172d2 100644 --- a/panda/src/pgraph/nodePath_ext.cxx +++ b/panda/src/pgraph/nodePath_ext.cxx @@ -59,8 +59,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const { PyObject *dupe = PyDict_GetItem(memo, self); if (dupe != nullptr) { // Already in the memo dictionary. - Py_INCREF(dupe); - return dupe; + return Py_NewRef(dupe); } NodePath *np_dupe; @@ -174,8 +173,7 @@ PyObject *Extension:: get_tags() const { // An empty NodePath returns None if (_this->is_empty()) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } // Just call PandaNode.tags rather than defining a whole new interface. @@ -323,8 +321,7 @@ get_tight_bounds(const NodePath &other) const { return Py_BuildValue("NN", min_inst, max_inst); } else { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } } diff --git a/panda/src/pgraph/pandaNode_ext.cxx b/panda/src/pgraph/pandaNode_ext.cxx index d4071ff4c6..cd7ca8b252 100644 --- a/panda/src/pgraph/pandaNode_ext.cxx +++ b/panda/src/pgraph/pandaNode_ext.cxx @@ -50,8 +50,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const { PyObject *dupe = PyDict_GetItem(memo, self); if (dupe != nullptr) { // Already in the memo dictionary. - Py_INCREF(dupe); - return dupe; + return Py_NewRef(dupe); } PT(PandaNode) node_dupe = _this->copy_subgraph(); @@ -94,9 +93,7 @@ get_tag_keys() const { */ PyObject *Extension:: get_python_tags() { - PyObject *dict = do_get_python_tags(); - Py_INCREF(dict); - return dict; + return Py_NewRef(do_get_python_tags()); } /** @@ -121,8 +118,7 @@ set_python_tag(PyObject *key, PyObject *value) { PyObject *Extension:: get_python_tag(PyObject *key) const { if (_this->_python_tag_data == nullptr) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } PyObject *dict = ((PythonTagDataImpl *)_this->_python_tag_data.p())->_dict; @@ -131,8 +127,7 @@ get_python_tag(PyObject *key) const { value = Py_None; } // PyDict_GetItem returns a borrowed reference. - Py_INCREF(value); - return value; + return Py_NewRef(value); } /** diff --git a/panda/src/pgraph/pythonLoaderFileType.cxx b/panda/src/pgraph/pythonLoaderFileType.cxx index ee6e23bbbc..9076a3535e 100644 --- a/panda/src/pgraph/pythonLoaderFileType.cxx +++ b/panda/src/pgraph/pythonLoaderFileType.cxx @@ -44,10 +44,9 @@ PythonLoaderFileType() { PythonLoaderFileType:: PythonLoaderFileType(std::string extension, PyObject *entry_point) : _extension(std::move(extension)), - _entry_point(entry_point) { + _entry_point(Py_NewRef(entry_point)) { init_type(); - Py_INCREF(entry_point); } /** @@ -314,8 +313,7 @@ load_file(const Filename &path, const LoaderOptions &options, record->ref(); PyTuple_SET_ITEM(args, 2, DTool_CreatePyInstanceTyped((void *)record, Dtool_BamCacheRecord, true, false, record->get_type_index())); } else { - PyTuple_SET_ITEM(args, 2, Py_None); - Py_INCREF(Py_None); + PyTuple_SET_ITEM(args, 2, Py_NewRef(Py_None)); } PT(PandaNode) node; diff --git a/panda/src/pgraph/renderState_ext.cxx b/panda/src/pgraph/renderState_ext.cxx index c7a9fe0672..6cfe05965e 100644 --- a/panda/src/pgraph/renderState_ext.cxx +++ b/panda/src/pgraph/renderState_ext.cxx @@ -96,8 +96,7 @@ get_composition_cache() const { PyObject *a, *b; const RenderState *source = _this->_composition_cache.get_key(i); if (source == nullptr) { - a = Py_None; - Py_INCREF(a); + a = Py_NewRef(Py_None); } else { source->ref(); a = DTool_CreatePyInstanceTyped((void *)source, Dtool_RenderState, @@ -105,8 +104,7 @@ get_composition_cache() const { } const RenderState *result = _this->_composition_cache.get_data(i)._result; if (result == nullptr) { - b = Py_None; - Py_INCREF(b); + b = Py_NewRef(Py_None); } else { result->ref(); b = DTool_CreatePyInstanceTyped((void *)result, Dtool_RenderState, @@ -144,8 +142,7 @@ get_invert_composition_cache() const { PyObject *a, *b; const RenderState *source = _this->_invert_composition_cache.get_key(i); if (source == nullptr) { - a = Py_None; - Py_INCREF(a); + a = Py_NewRef(Py_None); } else { source->ref(); a = DTool_CreatePyInstanceTyped((void *)source, Dtool_RenderState, @@ -153,8 +150,7 @@ get_invert_composition_cache() const { } const RenderState *result = _this->_invert_composition_cache.get_data(i)._result; if (result == nullptr) { - b = Py_None; - Py_INCREF(b); + b = Py_NewRef(Py_None); } else { result->ref(); b = DTool_CreatePyInstanceTyped((void *)result, Dtool_RenderState, diff --git a/panda/src/pgraph/transformState_ext.cxx b/panda/src/pgraph/transformState_ext.cxx index 10b629ddff..cc9ea28033 100644 --- a/panda/src/pgraph/transformState_ext.cxx +++ b/panda/src/pgraph/transformState_ext.cxx @@ -42,8 +42,7 @@ get_composition_cache() const { const TransformState *source = _this->_composition_cache.get_key(si); if (source == nullptr) { - a = Py_None; - Py_INCREF(a); + a = Py_NewRef(Py_None); } else { source->ref(); a = DTool_CreatePyInstanceTyped((void *)source, Dtool_TransformState, @@ -51,8 +50,7 @@ get_composition_cache() const { } const TransformState *result = _this->_composition_cache.get_data(si)._result; if (result == nullptr) { - b = Py_None; - Py_INCREF(b); + b = Py_NewRef(Py_None); } else { result->ref(); b = DTool_CreatePyInstanceTyped((void *)result, Dtool_TransformState, @@ -97,8 +95,7 @@ get_invert_composition_cache() const { const TransformState *source = _this->_invert_composition_cache.get_key(si); if (source == nullptr) { - a = Py_None; - Py_INCREF(a); + a = Py_NewRef(Py_None); } else { source->ref(); a = DTool_CreatePyInstanceTyped((void *)source, Dtool_TransformState, @@ -106,8 +103,7 @@ get_invert_composition_cache() const { } const TransformState *result = _this->_invert_composition_cache.get_data(si)._result; if (result == nullptr) { - b = Py_None; - Py_INCREF(b); + b = Py_NewRef(Py_None); } else { result->ref(); b = DTool_CreatePyInstanceTyped((void *)result, Dtool_TransformState, diff --git a/panda/src/pipeline/pythonThread.cxx b/panda/src/pipeline/pythonThread.cxx index 07c86ba413..84770c258e 100644 --- a/panda/src/pipeline/pythonThread.cxx +++ b/panda/src/pipeline/pythonThread.cxx @@ -27,8 +27,7 @@ PythonThread(PyObject *function, PyObject *args, const std::string &name, const std::string &sync_name) : Thread(name, sync_name) { - _function = function; - Py_INCREF(_function); + _function = Py_NewRef(function); _args = nullptr; _result = nullptr; @@ -78,14 +77,13 @@ PyObject *PythonThread:: join() { Thread::join(); - if (_result == nullptr) { + PyObject *result = _result; + if (result == nullptr) { // No result; return None. - Py_INCREF(Py_None); - return Py_None; + result = Py_None; } - Py_INCREF(_result); - return _result; + return Py_NewRef(result); } /** @@ -147,10 +145,7 @@ call_python_func(PyObject *function, PyObject *args) { PyObject *exc, *val, *tb; PyErr_Fetch(&exc, &val, &tb); - Py_XINCREF(exc); - Py_XINCREF(val); - Py_XINCREF(tb); - PyErr_Restore(exc, val, tb); + PyErr_Restore(Py_XNewRef(exc), Py_XNewRef(val), Py_XNewRef(tb)); PyErr_Print(); PyErr_Restore(exc, val, tb); @@ -206,10 +201,7 @@ call_python_func(PyObject *function, PyObject *args) { // Temporarily restore the exception state so we can print a callback // on-the-spot. - Py_XINCREF(exc); - Py_XINCREF(val); - Py_XINCREF(tb); - PyErr_Restore(exc, val, tb); + PyErr_Restore(Py_XNewRef(exc), Py_XNewRef(val), Py_XNewRef(tb)); PyErr_Print(); PyThreadState_Swap(orig_thread_state); @@ -252,10 +244,7 @@ call_python_func(PyObject *function, PyObject *args) { thread_cat.error() << "Exception occurred within " << *current_thread << "\n"; - Py_XINCREF(exc); - Py_XINCREF(val); - Py_XINCREF(tb); - PyErr_Restore(exc, val, tb); + PyErr_Restore(Py_XNewRef(exc), Py_XNewRef(val), Py_XNewRef(tb)); PyErr_Print(); } else { thread_cat.info() diff --git a/panda/src/pnmimage/pfmFile_ext.cxx b/panda/src/pnmimage/pfmFile_ext.cxx index baf1caf8e9..7aab96a2dc 100644 --- a/panda/src/pnmimage/pfmFile_ext.cxx +++ b/panda/src/pnmimage/pfmFile_ext.cxx @@ -63,8 +63,7 @@ get_points() const { default: Py_DECREF(list); - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } return list; @@ -92,10 +91,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { int channels = _this->get_num_channels(); int num_pixels = _this->get_x_size() * _this->get_y_size(); - if (self != nullptr) { - Py_INCREF(self); - } - view->obj = self; + view->obj = Py_XNewRef(self); view->buf = (void *) &(table[0]); view->len = 4 * table.size(); view->readonly = 1; diff --git a/panda/src/pstatclient/pStatClient_ext.cxx b/panda/src/pstatclient/pStatClient_ext.cxx index f78305f521..0724470cfb 100644 --- a/panda/src/pstatclient/pStatClient_ext.cxx +++ b/panda/src/pstatclient/pStatClient_ext.cxx @@ -107,7 +107,7 @@ make_python_frame_collector(PyFrameObject *frame, PyCodeObject *code) { } meth_name = PyUnicode_FromFormat("_%s%S", cls_name, meth_name); } else { - Py_INCREF(meth_name); + meth_name = Py_NewRef(meth_name); } if (!find_method(cls, meth_name, code)) { // Not a matching method object, it's something else. Forget it. diff --git a/panda/src/putil/bamReader_ext.cxx b/panda/src/putil/bamReader_ext.cxx index fce150f92c..308028cea3 100644 --- a/panda/src/putil/bamReader_ext.cxx +++ b/panda/src/putil/bamReader_ext.cxx @@ -135,8 +135,7 @@ read_object() { } if (ptr == nullptr) { - Py_INCREF(Py_None); - return Py_None; + return Py_NewRef(Py_None); } if (ref_ptr != nullptr) { @@ -165,15 +164,13 @@ get_file_version() const { */ void Extension:: register_factory(TypeHandle handle, PyObject *func) { - nassertv(func != nullptr); - if (!PyCallable_Check(func)) { Dtool_Raise_TypeError("second argument to register_factory must be callable"); return; } - Py_INCREF(func); - BamReader::get_factory()->register_factory(handle, &factory_callback, (void *)func); + void *user_data = (void *)Py_NewRef(func); + BamReader::get_factory()->register_factory(handle, &factory_callback, user_data); } #endif diff --git a/panda/src/putil/paramPyObject.I b/panda/src/putil/paramPyObject.I index 4099812974..3515226711 100644 --- a/panda/src/putil/paramPyObject.I +++ b/panda/src/putil/paramPyObject.I @@ -17,8 +17,7 @@ * Increments the reference count. Assumes the GIL is held. */ INLINE ParamPyObject:: -ParamPyObject(PyObject *value) : _value(value) { - Py_INCREF(value); +ParamPyObject(PyObject *value) : _value(Py_NewRef(value)) { } /** @@ -26,6 +25,5 @@ ParamPyObject(PyObject *value) : _value(value) { */ INLINE PyObject *ParamPyObject:: get_value() const { - Py_INCREF(_value); - return _value; + return Py_NewRef(_value); } diff --git a/panda/src/putil/pythonCallbackObject.cxx b/panda/src/putil/pythonCallbackObject.cxx index 666200fd3b..454c9bdaf5 100644 --- a/panda/src/putil/pythonCallbackObject.cxx +++ b/panda/src/putil/pythonCallbackObject.cxx @@ -37,8 +37,7 @@ extern struct Dtool_PyTypedObject Dtool_PythonCallbackObject; */ PythonCallbackObject:: PythonCallbackObject(PyObject *function) { - _function = Py_None; - Py_INCREF(_function); + _function = Py_NewRef(Py_None); set_function(function); @@ -69,8 +68,7 @@ PythonCallbackObject:: void PythonCallbackObject:: set_function(PyObject *function) { Py_DECREF(_function); - _function = function; - Py_INCREF(_function); + _function = Py_NewRef(function); if (_function != Py_None && !PyCallable_Check(_function)) { nassert_raise("Invalid function passed to PythonCallbackObject"); } @@ -81,8 +79,7 @@ set_function(PyObject *function) { */ PyObject *PythonCallbackObject:: get_function() { - Py_INCREF(_function); - return _function; + return Py_NewRef(_function); } /** @@ -90,7 +87,7 @@ get_function() { */ PyObject *PythonCallbackObject:: __reduce__() const { - return Py_BuildValue("O(O)", (PyObject *)&Dtool_PythonCallbackObject, _function); + return Py_BuildValue("O(O)", (PyObject *)&Dtool_PythonCallbackObject._PyType, _function); } /** diff --git a/panda/src/putil/typedWritable_ext.cxx b/panda/src/putil/typedWritable_ext.cxx index 501a07a600..a61bcdfac4 100644 --- a/panda/src/putil/typedWritable_ext.cxx +++ b/panda/src/putil/typedWritable_ext.cxx @@ -149,8 +149,7 @@ wrap_typed_writable(void *from_this, PyTypeObject *from_type) { } nassertr(to_this->_self != nullptr, nullptr); - Py_INCREF(to_this->_self); - return to_this->_self; + return Py_NewRef(to_this->_self); } /** @@ -212,8 +211,8 @@ __new__(PyTypeObject *cls) { // Make sure that the bindings know how to obtain a wrapper for this type. TypeRegistry *registry = TypeRegistry::ptr(); - registry->record_python_type(*handle, cls, &wrap_typed_writable); - Py_INCREF(cls); + PyTypeObject *cls_ref = (PyTypeObject *)Py_NewRef((PyObject *)cls); + registry->record_python_type(*handle, cls_ref, &wrap_typed_writable); // Note that we don't increment the reference count here, because that would // create a memory leak. The TypedWritableProxy gets deleted when the Python diff --git a/pandatool/src/deploy-stub/android_log.c b/pandatool/src/deploy-stub/android_log.c index 209515f90d..83b6090111 100644 --- a/pandatool/src/deploy-stub/android_log.c +++ b/pandatool/src/deploy-stub/android_log.c @@ -28,11 +28,9 @@ _py_write(PyObject *self, PyObject *args) { char *text; if (PyArg_ParseTuple(args, "iss", &prio, &tag, &text)) { __android_log_write(prio, tag, text); - Py_INCREF(Py_None); - return Py_None; + Py_RETURN_NONE; } return NULL; - } static PyMethodDef python_simple_funcs[] = {