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
This commit is contained in:
rdb 2024-01-29 17:35:41 +01:00
parent f1f15a92a4
commit 73360393df
44 changed files with 217 additions and 380 deletions

View File

@ -41,9 +41,7 @@ void Extension<DCClass>::
set_class_def(PyObject *class_def) { set_class_def(PyObject *class_def) {
PythonClassDefsImpl *defs = do_get_defs(); PythonClassDefsImpl *defs = do_get_defs();
Py_XINCREF(class_def); Py_XSETREF(defs->_class_def, Py_XNewRef(class_def));
Py_XDECREF(defs->_class_def);
defs->_class_def = class_def;
} }
/** /**
@ -53,13 +51,11 @@ set_class_def(PyObject *class_def) {
PyObject *Extension<DCClass>:: PyObject *Extension<DCClass>::
get_class_def() const { get_class_def() const {
if (!has_class_def()) { if (!has_class_def()) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
PythonClassDefsImpl *defs = do_get_defs(); PythonClassDefsImpl *defs = do_get_defs();
Py_INCREF(defs->_class_def); return Py_NewRef(defs->_class_def);
return defs->_class_def;
} }
/** /**
@ -80,9 +76,7 @@ void Extension<DCClass>::
set_owner_class_def(PyObject *owner_class_def) { set_owner_class_def(PyObject *owner_class_def) {
PythonClassDefsImpl *defs = do_get_defs(); PythonClassDefsImpl *defs = do_get_defs();
Py_XINCREF(owner_class_def); Py_XSETREF(defs->_owner_class_def, Py_XNewRef(owner_class_def));
Py_XDECREF(defs->_owner_class_def);
defs->_owner_class_def = owner_class_def;
} }
/** /**
@ -92,13 +86,11 @@ set_owner_class_def(PyObject *owner_class_def) {
PyObject *Extension<DCClass>:: PyObject *Extension<DCClass>::
get_owner_class_def() const { get_owner_class_def() const {
if (!has_owner_class_def()) { if (!has_owner_class_def()) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
PythonClassDefsImpl *defs = do_get_defs(); PythonClassDefsImpl *defs = do_get_defs();
Py_INCREF(defs->_owner_class_def); return Py_NewRef(defs->_owner_class_def);
return defs->_owner_class_def;
} }
/** /**

View File

@ -173,8 +173,7 @@ unpack_object() {
switch (pack_type) { switch (pack_type) {
case PT_invalid: case PT_invalid:
object = Py_None; object = Py_NewRef(Py_None);
Py_INCREF(object);
_this->unpack_skip(); _this->unpack_skip();
break; break;

View File

@ -725,9 +725,9 @@ handle_update_field() {
// while we call the update method--otherwise, the update method might // while we call the update method--otherwise, the update method might
// get into trouble if it tried to delete the object from the doId2do // get into trouble if it tried to delete the object from the doId2do
// map. // map.
Py_INCREF(distobj); PyObject *distobj_ref = Py_NewRef(distobj);
invoke_extension(dclass).receive_update(distobj, _di); invoke_extension(dclass).receive_update(distobj_ref, _di);
Py_DECREF(distobj); Py_DECREF(distobj_ref);
if (PyErr_Occurred()) { if (PyErr_Occurred()) {
#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) #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 // raised while we call the update method--otherwise, the update
// method might get into trouble if it tried to delete the object from // method might get into trouble if it tried to delete the object from
// the doId2do map. // 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 // make a copy of the datagram iterator so that we can use the main
// iterator for the non-owner update // iterator for the non-owner update
DatagramIterator _odi(_di); DatagramIterator _odi(_di);
invoke_extension(dclass).receive_update(distobjOV, _odi); invoke_extension(dclass).receive_update(distobjOV_ref, _odi);
Py_DECREF(distobjOV); Py_DECREF(distobjOV_ref);
if (PyErr_Occurred()) { if (PyErr_Occurred()) {
#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) #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 // while we call the update method--otherwise, the update method might
// get into trouble if it tried to delete the object from the doId2do // get into trouble if it tried to delete the object from the doId2do
// map. // map.
Py_INCREF(distobj); PyObject *distobj_ref = Py_NewRef(distobj);
invoke_extension(dclass).receive_update(distobj, _di); invoke_extension(dclass).receive_update(distobj_ref, _di);
Py_DECREF(distobj); Py_DECREF(distobj_ref);
if (PyErr_Occurred()) { if (PyErr_Occurred()) {
#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) #if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS)

View File

@ -32,8 +32,7 @@ static PyObject *gen_next(PyObject *self) {
if (ival->get_state() != CInterval::S_final) { if (ival->get_state() != CInterval::S_final) {
// Try again next frame. // Try again next frame.
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
else { else {
PyErr_SetNone(PyExc_StopIteration); PyErr_SetNone(PyExc_StopIteration);

View File

@ -147,14 +147,12 @@ py_is_frozen_module(PyObject *self, PyObject *args) {
i = 0; i = 0;
while (PyImport_FrozenModules[i].name != NULL) { while (PyImport_FrozenModules[i].name != NULL) {
if (strcmp(PyImport_FrozenModules[i].name, name) == 0) { if (strcmp(PyImport_FrozenModules[i].name, name) == 0) {
Py_INCREF(Py_True); Py_RETURN_TRUE;
return Py_True;
} }
++i; ++i;
} }
Py_INCREF(Py_False); Py_RETURN_FALSE;
return Py_False;
} }
/* /*

View File

@ -134,8 +134,7 @@ PyObject *Extension<Filename>::
scan_directory() const { scan_directory() const {
vector_string contents; vector_string contents;
if (!_this->scan_directory(contents)) { if (!_this->scan_directory(contents)) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
PyObject *result = PyList_New(contents.size()); PyObject *result = PyList_New(contents.size());

View File

@ -797,9 +797,7 @@ write_python_instance(ostream &out, int indent_level, const string &return_expr,
indent(out, indent_level) indent(out, indent_level)
<< "if (" << return_expr << " == nullptr) {\n"; << "if (" << return_expr << " == nullptr) {\n";
indent(out, indent_level) indent(out, indent_level)
<< " Py_INCREF(Py_None);\n"; << " return Py_NewRef(Py_None);\n";
indent(out, indent_level)
<< " return Py_None;\n";
indent(out, indent_level) indent(out, indent_level)
<< "} else {\n"; << "} else {\n";
// Special exception if we are returning TypedWritable, which might // 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; class_ptr = "(PyObject *)" + class_ptr;
// Note: PyModule_AddObject steals a reference, so we have to call Py_INCREF // The first time we add something to a module, we use PyModule_AddObject,
// for every but the first time we add it to the module. // which steals a reference. This saves a call to Py_DECREF.
if (obj->_itype.is_typedef()) { if (!obj->_itype.is_typedef()) {
out << " Py_INCREF(" << class_ptr << ");\n"; 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) { if (export_class_name != export_class_name2) {
out << " Py_INCREF(Dtool_Ptr_" << class_name << ");\n"; out << " PyModule_AddObjectRef(module, \"" << export_class_name2 << "\", " << class_ptr << ");\n";
out << " PyModule_AddObject(module, \"" << export_class_name2 << "\", " << class_ptr << ");\n";
} }
} }
@ -2038,8 +2035,7 @@ write_module_class(ostream &out, Object *obj) {
out << " }\n"; out << " }\n";
} }
out << " Py_INCREF(Py_NotImplemented);\n"; out << " return Py_NewRef(Py_NotImplemented);\n";
out << " return Py_NotImplemented;\n";
out << "}\n\n"; out << "}\n\n";
} }
break; break;
@ -2508,8 +2504,7 @@ write_module_class(ostream &out, Object *obj) {
// of raising an exception, if the this pointer doesn't match. This // of raising an exception, if the this pointer doesn't match. This
// is for things like __pow__, which Python likes to call on the // is for things like __pow__, which Python likes to call on the
// wrong-type objects. // wrong-type objects.
out << " Py_INCREF(Py_NotImplemented);\n"; out << " return Py_NewRef(Py_NotImplemented);\n";
out << " return Py_NotImplemented;\n";
out << " }\n"; out << " }\n";
set<FunctionRemap*> one_param_remaps; set<FunctionRemap*> one_param_remaps;
@ -2862,8 +2857,7 @@ write_module_class(ostream &out, Object *obj) {
has_local_richcompare = true; has_local_richcompare = true;
} }
out << " Py_INCREF(Py_NotImplemented);\n"; out << " return Py_NewRef(Py_NotImplemented);\n";
out << " return Py_NotImplemented;\n";
out << "}\n\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())) { 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 { } else {
return_expr = manage_return_value(out, indent_level, remap, "return_value"); 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) { } else if (return_flags & RF_self) {
indent(out, indent_level) << "Py_INCREF(self);\n"; indent(out, indent_level) << "return Py_NewRef(self);\n";
indent(out, indent_level) << "return self;\n";
} else if (return_flags & RF_richcompare_zero) { } else if (return_flags & RF_richcompare_zero) {
indent(out, indent_level) indent(out, indent_level)
@ -6497,8 +6490,7 @@ write_function_instance(ostream &out, FunctionRemap *remap,
} else if (return_flags & RF_pyobject) { } else if (return_flags & RF_pyobject) {
if (return_expr.empty()) { if (return_expr.empty()) {
indent(out, indent_level) << "Py_INCREF(Py_None);\n"; indent(out, indent_level) << "return Py_NewRef(Py_None);\n";
indent(out, indent_level) << "return Py_None;\n";
} else if (return_flags & RF_preserve_null) { } else if (return_flags & RF_preserve_null) {
indent(out, indent_level) << "if (" << return_expr << " == nullptr) {\n"; 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"; indent(out, indent_level) << "return -1;\n";
} else if (return_flags & RF_err_notimplemented) { } else if (return_flags & RF_err_notimplemented) {
indent(out, indent_level) << "Py_INCREF(Py_NotImplemented);\n"; indent(out, indent_level) << "return Py_NewRef(Py_NotImplemented);\n";
indent(out, indent_level) << "return Py_NotImplemented;\n";
} else if (return_flags & RF_err_null) { } else if (return_flags & RF_err_null) {
indent(out, indent_level) << "return nullptr;\n"; 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"; indent(out, indent_level) << "return -1;\n";
} else if (return_flags & RF_err_notimplemented) { } else if (return_flags & RF_err_notimplemented) {
indent(out, indent_level) << "Py_INCREF(Py_NotImplemented);\n"; indent(out, indent_level) << "return Py_NewRef(Py_NotImplemented);\n";
indent(out, indent_level) << "return Py_NotImplemented;\n";
} else if (return_flags & RF_err_null) { } else if (return_flags & RF_err_null) {
indent(out, indent_level) << "return nullptr;\n"; indent(out, indent_level) << "return nullptr;\n";
@ -6991,8 +6981,7 @@ write_getset(ostream &out, Object *obj, Property *property) {
/*if (property->_has_function != NULL) { /*if (property->_has_function != NULL) {
out << " if (!local_this->" << property->_has_function->_ifunc.get_name() << "(index)) {\n" out << " if (!local_this->" << property->_has_function->_ifunc.get_name() << "(index)) {\n"
<< " Py_INCREF(Py_None);\n" << " return Py_NewRef(Py_None);\n"
<< " return Py_None;\n"
<< " }\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. // We have to create an args tuple only to unpack it later, ugh.
out << " PyObject *args = PyTuple_New(2);\n" out << " PyObject *args = PyTuple_New(2);\n"
<< " PyTuple_SET_ITEM(args, 0, key);\n" << " PyTuple_SET_ITEM(args, 0, Py_NewRef(key));\n"
<< " PyTuple_SET_ITEM(args, 1, value);\n" << " PyTuple_SET_ITEM(args, 1, Py_NewRef(value));\n";
<< " Py_INCREF(key);\n"
<< " Py_INCREF(value);\n";
string expected_params; string expected_params;
if (!write_function_forset(out, remaps, 2, 2, if (!write_function_forset(out, remaps, 2, 2,
@ -7423,8 +7410,7 @@ write_getset(ostream &out, Object *obj, Property *property) {
} else { } else {
out << " if (!" << cClassName << "::" << property->_has_function->_ifunc.get_name() << "()) {\n"; out << " if (!" << cClassName << "::" << property->_has_function->_ifunc.get_name() << "()) {\n";
} }
out << " Py_INCREF(Py_None);\n" out << " return Py_NewRef(Py_None);\n"
<< " return Py_None;\n"
<< " }\n"; << " }\n";
} }

View File

@ -27,15 +27,13 @@ static PyMemberDef standard_type_members[] = {
static PyObject *GetSuperBase(PyObject *self) { static PyObject *GetSuperBase(PyObject *self) {
Dtool_PyTypedObject *super_base = Dtool_GetSuperBase(); Dtool_PyTypedObject *super_base = Dtool_GetSuperBase();
Py_XINCREF((PyTypeObject *)super_base); // order is important .. this is used for static functions return Py_XNewRef((PyObject *)&super_base->_PyType);
return (PyObject *)super_base;
}; };
static void Dtool_PyModuleClassInit_DTOOL_SUPER_BASE(PyObject *module) { static void Dtool_PyModuleClassInit_DTOOL_SUPER_BASE(PyObject *module) {
if (module != nullptr) { if (module != nullptr) {
Dtool_PyTypedObject *super_base = Dtool_GetSuperBase(); Dtool_PyTypedObject *super_base = Dtool_GetSuperBase();
Py_INCREF((PyTypeObject *)&super_base); PyModule_AddObjectRef(module, "DTOOL_SUPER_BASE", (PyObject *)&super_base->_PyType);
PyModule_AddObject(module, "DTOOL_SUPER_BASE", (PyObject *)&super_base);
} }
} }
@ -152,7 +150,7 @@ Dtool_PyTypedObject *Dtool_GetSuperBase() {
PyErr_SetString(PyExc_TypeError, "PyType_Ready(Dtool_DTOOL_SUPER_BASE)"); PyErr_SetString(PyExc_TypeError, "PyType_Ready(Dtool_DTOOL_SUPER_BASE)");
return nullptr; 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)); PyDict_SetItemString(super_base_type._PyType.tp_dict, "DtoolGetSuperBase", PyCFunction_New(&methods[0], (PyObject *)&super_base_type));

View File

@ -241,6 +241,28 @@ INLINE PyObject *PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObje
} }
#endif #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 */ /* Python 3.12 */
#if PY_VERSION_HEX < 0x030C0000 #if PY_VERSION_HEX < 0x030C0000

View File

@ -97,8 +97,7 @@ ALWAYS_INLINE void
Dtool_Assign_PyObject(PyObject *&ptr, PyObject *value) { Dtool_Assign_PyObject(PyObject *&ptr, PyObject *value) {
PyObject *prev_value = ptr; PyObject *prev_value = ptr;
if (prev_value != value) { if (prev_value != value) {
Py_XINCREF(value); ptr = Py_XNewRef(value);
ptr = value;
Py_XDECREF(prev_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) { ALWAYS_INLINE PyObject *Dtool_WrapValue(bool value) {
PyObject *result = (value ? Py_True : Py_False); PyObject *result = (value ? Py_True : Py_False);
Py_INCREF(result); return Py_NewRef(result);
return result;
} }
ALWAYS_INLINE PyObject *Dtool_WrapValue(double value) { 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) { ALWAYS_INLINE PyObject *Dtool_WrapValue(const char *value) {
if (value == nullptr) { if (value == nullptr) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} else { } else {
#if PY_MAJOR_VERSION >= 3 #if PY_MAJOR_VERSION >= 3
return PyUnicode_FromString(value); 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) { ALWAYS_INLINE PyObject *Dtool_WrapValue(const wchar_t *value) {
if (value == nullptr) { if (value == nullptr) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} else { } else {
return PyUnicode_FromWideChar(value, (Py_ssize_t)wcslen(value)); 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) { ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::string *value) {
if (value == nullptr) { if (value == nullptr) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} else { } else {
#if PY_MAJOR_VERSION >= 3 #if PY_MAJOR_VERSION >= 3
return PyUnicode_FromStringAndSize(value->data(), (Py_ssize_t)value->length()); 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) { ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::wstring *value) {
if (value == nullptr) { if (value == nullptr) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} else { } else {
return PyUnicode_FromWideChar(value->data(), (Py_ssize_t)value->length()); 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) { ALWAYS_INLINE PyObject *Dtool_WrapValue(std::nullptr_t) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
ALWAYS_INLINE PyObject *Dtool_WrapValue(PyObject *value) { ALWAYS_INLINE PyObject *Dtool_WrapValue(PyObject *value) {

View File

@ -273,8 +273,7 @@ PyObject *_Dtool_Return_None() {
return Dtool_Raise_AssertionError(); return Dtool_Raise_AssertionError();
} }
#endif #endif
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
/** /**
@ -290,9 +289,7 @@ PyObject *Dtool_Return_Bool(bool value) {
return Dtool_Raise_AssertionError(); return Dtool_Raise_AssertionError();
} }
#endif #endif
PyObject *result = (value ? Py_True : Py_False); return Py_NewRef(value ? Py_True : Py_False);
Py_INCREF(result);
return result;
} }
/** /**
@ -325,8 +322,7 @@ static PyObject *Dtool_EnumType_New(PyTypeObject *subtype, PyObject *args, PyObj
} }
if (Py_TYPE(arg) == subtype) { if (Py_TYPE(arg) == subtype) {
Py_INCREF(arg); return Py_NewRef(arg);
return arg;
} }
PyObject *value2member = PyDict_GetItemString(subtype->tp_dict, "_value2member_map_"); 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); PyObject *member = PyDict_GetItem(value2member, arg);
if (member != nullptr) { if (member != nullptr) {
Py_INCREF(member); return Py_NewRef(member);
return member;
} }
PyObject *repr = PyObject_Repr(arg); 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_"); value2member_map_sunder_str = PyString_InternFromString("_value2member_map_");
#endif #endif
PyObject *name_value_tuple = PyTuple_New(4); PyObject *name_value_tuple = PyTuple_New(4);
PyTuple_SET_ITEM(name_value_tuple, 0, name_str); PyTuple_SET_ITEM(name_value_tuple, 0, Py_NewRef(name_str));
PyTuple_SET_ITEM(name_value_tuple, 1, value_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, 2, name_sunder_str);
PyTuple_SET_ITEM(name_value_tuple, 3, value_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(); PyObject *slots_dict = PyDict_New();
PyDict_SetItemString(slots_dict, "__slots__", name_value_tuple); 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) { if (local_this == nullptr) {
// This is actually a very common case, so let's allow this, but return // This is actually a very common case, so let's allow this, but return
// Py_None consistently. This eliminates code in the wrappers. // Py_None consistently. This eliminates code in the wrappers.
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
Dtool_PyInstDef *self = (Dtool_PyInstDef *)PyType_GenericAlloc(&in_classdef._PyType, 0); 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->_is_const = from->_is_const;
to->_ptr_to_object = from->_ptr_to_object; to->_ptr_to_object = from->_ptr_to_object;
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
return PyErr_Format(PyExc_TypeError, "types %s and %s do not match", 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()) { if (PyErr_Occurred()) {
return nullptr; return nullptr;
} }
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
/** /**

View File

@ -237,7 +237,7 @@ EXPCL_PYPANDA PyObject *Dtool_Return_Bool(bool value);
EXPCL_PYPANDA PyObject *_Dtool_Return(PyObject *value); EXPCL_PYPANDA PyObject *_Dtool_Return(PyObject *value);
#ifdef NDEBUG #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) #define Dtool_Return(value) (LIKELY(PyErr_Occurred() == nullptr) ? value : nullptr)
#else #else
#define Dtool_Return_None() _Dtool_Return_None() #define Dtool_Return_None() _Dtool_Return_None()

View File

@ -243,8 +243,7 @@ static PyObject *Dtool_MutableSequenceWrapper_clear(PyObject *self, PyObject *)
return nullptr; return nullptr;
} }
} }
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
/** /**
@ -270,8 +269,7 @@ static PyObject *Dtool_MutableSequenceWrapper_remove(PyObject *self, PyObject *v
int cmp = PyObject_RichCompareBool(item, value, Py_EQ); int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
if (cmp > 0) { if (cmp > 0) {
if (wrap->_setitem_func(wrap->_base._self, index, nullptr) == 0) { if (wrap->_setitem_func(wrap->_base._self, index, nullptr) == 0) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} else { } else {
return nullptr; return nullptr;
} }
@ -405,8 +403,7 @@ static PyObject *Dtool_MutableSequenceWrapper_extend(PyObject *self, PyObject *a
} }
Py_DECREF(iter); Py_DECREF(iter);
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
/** /**
@ -481,8 +478,7 @@ static PyObject *Dtool_MappingWrapper_get(PyObject *self, PyObject *args) {
return value; return value;
} else if (PyErr_ExceptionMatches(PyExc_KeyError)) { } else if (PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear(); PyErr_Clear();
Py_INCREF(defvalue); return Py_NewRef(defvalue);
return defvalue;
} else { } else {
return nullptr; return nullptr;
} }
@ -604,8 +600,7 @@ static PyObject *Dtool_MappingWrapper_keys(PyObject *self, PyObject *) {
} }
(void)PyObject_INIT(keys, &wrapper_type); (void)PyObject_INIT(keys, &wrapper_type);
Py_XINCREF(wrap->_base._self); keys->_base._self = Py_XNewRef(wrap->_base._self);
keys->_base._self = wrap->_base._self;
keys->_base._name = wrap->_base._name; keys->_base._name = wrap->_base._name;
keys->_keys._len_func = wrap->_keys._len_func; keys->_keys._len_func = wrap->_keys._len_func;
keys->_keys._getitem_func = wrap->_keys._getitem_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); (void)PyObject_INIT(values, &wrapper_type);
Py_XINCREF(wrap->_base._self); values->_base._self = Py_XNewRef(wrap->_base._self);
values->_base._self = wrap->_base._self;
values->_base._name = wrap->_base._name; values->_base._name = wrap->_base._name;
values->_keys._len_func = wrap->_keys._len_func; values->_keys._len_func = wrap->_keys._len_func;
values->_keys._getitem_func = wrap->_keys._getitem_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); (void)PyObject_INIT(items, &wrapper_type);
Py_XINCREF(wrap->_base._self); items->_base._self = Py_XNewRef(wrap->_base._self);
items->_base._self = wrap->_base._self;
items->_base._name = wrap->_base._name; items->_base._name = wrap->_base._name;
items->_keys._len_func = wrap->_keys._len_func; items->_keys._len_func = wrap->_keys._len_func;
items->_keys._getitem_func = wrap->_keys._getitem_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)) { } else if (PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear(); PyErr_Clear();
Py_INCREF(defvalue); return Py_NewRef(defvalue);
return defvalue;
} else { } else {
return nullptr; return nullptr;
} }
@ -1014,8 +1006,7 @@ static PyObject *Dtool_MutableMappingWrapper_clear(PyObject *self, PyObject *) {
} }
} }
} }
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
/** /**
@ -1046,8 +1037,7 @@ static PyObject *Dtool_MutableMappingWrapper_setdefault(PyObject *self, PyObject
} else if (PyErr_ExceptionMatches(PyExc_KeyError)) { } else if (PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear(); PyErr_Clear();
if (wrap->_setitem_func(wrap->_base._self, key, defvalue) == 0) { if (wrap->_setitem_func(wrap->_base._self, key, defvalue) == 0) {
Py_INCREF(defvalue); return Py_NewRef(defvalue);
return defvalue;
} }
} }
return nullptr; return nullptr;
@ -1071,8 +1061,7 @@ static PyObject *Dtool_MutableMappingWrapper_update(PyObject *self, PyObject *ar
case 0: case 0:
if (kwargs == nullptr) { if (kwargs == nullptr) {
// This is legal. // This is legal.
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
dict = kwargs; dict = kwargs;
break; break;
@ -1093,8 +1082,7 @@ static PyObject *Dtool_MutableMappingWrapper_update(PyObject *self, PyObject *ar
return nullptr; return nullptr;
} }
} }
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
/** /**
@ -1276,8 +1264,7 @@ Dtool_SequenceWrapper *Dtool_NewSequenceWrapper(PyObject *self, const char *name
} }
(void)PyObject_INIT(wrap, &wrapper_type); (void)PyObject_INIT(wrap, &wrapper_type);
Py_XINCREF(self); wrap->_base._self = Py_XNewRef(self);
wrap->_base._self = self;
wrap->_base._name = name; wrap->_base._name = name;
wrap->_len_func = nullptr; wrap->_len_func = nullptr;
wrap->_getitem_func = nullptr; wrap->_getitem_func = nullptr;
@ -1387,8 +1374,7 @@ Dtool_MutableSequenceWrapper *Dtool_NewMutableSequenceWrapper(PyObject *self, co
} }
(void)PyObject_INIT(wrap, &wrapper_type); (void)PyObject_INIT(wrap, &wrapper_type);
Py_XINCREF(self); wrap->_base._self = Py_XNewRef(self);
wrap->_base._self = self;
wrap->_base._name = name; wrap->_base._name = name;
wrap->_len_func = nullptr; wrap->_len_func = nullptr;
wrap->_getitem_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); (void)PyObject_INIT(wrap, &wrapper_type);
Py_XINCREF(self); wrap->_base._self = Py_XNewRef(self);
wrap->_base._self = self;
wrap->_base._name = name; wrap->_base._name = name;
wrap->_keys._len_func = nullptr; wrap->_keys._len_func = nullptr;
wrap->_keys._getitem_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); (void)PyObject_INIT(wrap, &wrapper_type);
Py_XINCREF(self); wrap->_base._self = Py_XNewRef(self);
wrap->_base._self = self;
wrap->_base._name = name; wrap->_base._name = name;
wrap->_keys._len_func = nullptr; wrap->_keys._len_func = nullptr;
wrap->_keys._getitem_func = nullptr; wrap->_keys._getitem_func = nullptr;
@ -1700,8 +1684,7 @@ Dtool_NewGenerator(PyObject *self, iternextfunc gen_next) {
Dtool_GeneratorWrapper *gen; Dtool_GeneratorWrapper *gen;
gen = (Dtool_GeneratorWrapper *)PyType_GenericAlloc(&wrapper_type, 0); gen = (Dtool_GeneratorWrapper *)PyType_GenericAlloc(&wrapper_type, 0);
if (gen != nullptr) { if (gen != nullptr) {
Py_INCREF(self); gen->_base._self = Py_NewRef(self);
gen->_base._self = self;
gen->_iternext_func = gen_next; gen->_iternext_func = gen_next;
} }
return (PyObject *)gen; return (PyObject *)gen;

View File

@ -32,8 +32,7 @@ __reduce__(PyObject *self) const {
PyTuple_SET_ITEM(nodepaths, i++, PyTuple_SET_ITEM(nodepaths, i++,
DTool_CreatePyInstance((void *)center, Dtool_NodePath, false, true)); DTool_CreatePyInstance((void *)center, Dtool_NodePath, false, true));
} else { } else {
PyTuple_SET_ITEM(nodepaths, i++, Py_None); PyTuple_SET_ITEM(nodepaths, i++, Py_NewRef(Py_None));
Py_INCREF(Py_None);
} }
CollisionHandlerPhysical::Colliders::const_iterator it; CollisionHandlerPhysical::Colliders::const_iterator it;

View File

@ -26,8 +26,7 @@ PythonGraphicsWindowProc::
PythonGraphicsWindowProc(PyObject* function, PyObject* name) : PythonGraphicsWindowProc(PyObject* function, PyObject* name) :
PythonCallbackObject(function) PythonCallbackObject(function)
{ {
_name = name; _name = Py_NewRef(name);
Py_INCREF(_name);
} }
/** /**

View File

@ -84,8 +84,7 @@ static PyObject *get_done_result(const AsyncFuture *future) {
future->get_result(ptr, ref_ptr); future->get_result(ptr, ref_ptr);
if (ptr == nullptr) { if (ptr == nullptr) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
TypeHandle type = ptr->get_type(); TypeHandle type = ptr->get_type();
@ -141,9 +140,9 @@ static PyObject *gen_next(PyObject *self) {
if (!future->done()) { if (!future->done()) {
// Continue awaiting the result. // Continue awaiting the result.
Py_INCREF(self); return Py_NewRef(self);
return self; }
} else { else {
PyObject *result = get_done_result(future); PyObject *result = get_done_result(future);
if (result != nullptr) { if (result != nullptr) {
PyErr_SetObject(PyExc_StopIteration, result); PyErr_SetObject(PyExc_StopIteration, result);
@ -323,8 +322,7 @@ add_done_callback(PyObject *self, PyObject *fn) {
_this->add_waiting_task(task); _this->add_waiting_task(task);
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
/** /**

View File

@ -16,8 +16,7 @@
*/ */
INLINE PyObject *PythonTask:: INLINE PyObject *PythonTask::
get_function() { get_function() {
Py_INCREF(_function); return Py_NewRef(_function);
return _function;
} }
/** /**
@ -25,8 +24,7 @@ get_function() {
*/ */
INLINE PyObject *PythonTask:: INLINE PyObject *PythonTask::
get_upon_death() { get_upon_death() {
Py_INCREF(_upon_death); return Py_NewRef(_upon_death);
return _upon_death;
} }
/** /**
@ -34,8 +32,7 @@ get_upon_death() {
*/ */
INLINE PyObject *PythonTask:: INLINE PyObject *PythonTask::
get_owner() const { get_owner() const {
Py_INCREF(_owner); return Py_NewRef(_owner);
return _owner;
} }
/** /**
@ -50,7 +47,5 @@ set_result(PyObject *result) {
nassertv(is_alive()); nassertv(is_alive());
nassertv(!done()); nassertv(!done());
nassertv(_exception == nullptr); nassertv(_exception == nullptr);
Py_INCREF(result); Py_XSETREF(_exc_value, Py_NewRef(result));
Py_XDECREF(_exc_value);
_exc_value = result;
} }

View File

@ -51,17 +51,17 @@ PythonTask(PyObject *func_or_coro, const std::string &name) :
nassertv(func_or_coro != nullptr); nassertv(func_or_coro != nullptr);
if (func_or_coro == Py_None || PyCallable_Check(func_or_coro)) { if (func_or_coro == Py_None || PyCallable_Check(func_or_coro)) {
_function = func_or_coro; _function = Py_NewRef(func_or_coro);
Py_INCREF(_function); }
} else if (PyCoro_CheckExact(func_or_coro)) { else if (PyCoro_CheckExact(func_or_coro)) {
// We also allow passing in a coroutine, because why not. // We also allow passing in a coroutine, because why not.
_generator = func_or_coro; _generator = Py_NewRef(func_or_coro);
Py_INCREF(_generator); }
} else if (PyGen_CheckExact(func_or_coro)) { else if (PyGen_CheckExact(func_or_coro)) {
// Something emulating a coroutine. // Something emulating a coroutine.
_generator = func_or_coro; _generator = Py_NewRef(func_or_coro);
Py_INCREF(_generator); }
} else { else {
nassert_raise("Invalid function passed to PythonTask"); nassert_raise("Invalid function passed to PythonTask");
} }
@ -114,10 +114,8 @@ PythonTask::
*/ */
void PythonTask:: void PythonTask::
set_function(PyObject *function) { 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)) { if (_function != Py_None && !PyCallable_Check(_function)) {
nassert_raise("Invalid function passed to PythonTask"); nassert_raise("Invalid function passed to PythonTask");
} }
@ -165,18 +163,16 @@ get_args() {
PyObject *with_task = PyTuple_New(num_args + 1); PyObject *with_task = PyTuple_New(num_args + 1);
for (int i = 0; i < num_args; ++i) { for (int i = 0; i < num_args; ++i) {
PyObject *item = PyTuple_GET_ITEM(_args, i); PyObject *item = PyTuple_GET_ITEM(_args, i);
Py_INCREF(item); PyTuple_SET_ITEM(with_task, i, Py_NewRef(item));
PyTuple_SET_ITEM(with_task, i, item);
} }
this->ref(); this->ref();
PyObject *self = DTool_CreatePyInstance(this, Dtool_PythonTask, true, false); PyObject *self = DTool_CreatePyInstance(this, Dtool_PythonTask, true, false);
PyTuple_SET_ITEM(with_task, num_args, self); PyTuple_SET_ITEM(with_task, num_args, self);
return with_task; return with_task;
}
} else { else {
Py_INCREF(_args); return Py_NewRef(_args);
return _args;
} }
} }
@ -186,10 +182,8 @@ get_args() {
*/ */
void PythonTask:: void PythonTask::
set_upon_death(PyObject *upon_death) { 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)) { if (_upon_death != Py_None && !PyCallable_Check(_upon_death)) {
nassert_raise("Invalid upon_death function passed to PythonTask"); nassert_raise("Invalid upon_death function passed to PythonTask");
} }
@ -234,9 +228,7 @@ set_owner(PyObject *owner) {
unregister_from_owner(); unregister_from_owner();
} }
Py_XDECREF(_owner); Py_XSETREF(_owner, Py_NewRef(owner));
_owner = owner;
Py_INCREF(_owner);
if (_owner != Py_None && _state != S_inactive) { if (_owner != Py_None && _state != S_inactive) {
register_to_owner(); register_to_owner();
@ -254,14 +246,11 @@ get_result() const {
if (_exception == nullptr) { if (_exception == nullptr) {
// The result of the call is stored in _exc_value. // The result of the call is stored in _exc_value.
Py_XINCREF(_exc_value); return Py_XNewRef(_exc_value);
return _exc_value; }
} else { else {
_retrieved_exception = true; _retrieved_exception = true;
Py_INCREF(_exception); PyErr_Restore(Py_NewRef(_exception), Py_XNewRef(_exc_value), Py_XNewRef(_exc_traceback));
Py_XINCREF(_exc_value);
Py_XINCREF(_exc_traceback);
PyErr_Restore(_exception, _exc_value, _exc_traceback);
return nullptr; return nullptr;
} }
} }
@ -273,13 +262,15 @@ get_result() const {
/*PyObject *PythonTask:: /*PyObject *PythonTask::
exception() const { exception() const {
if (_exception == nullptr) { if (_exception == nullptr) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None; }
} else if (_exc_value == nullptr || _exc_value == Py_None) { else if (_exc_value == nullptr || _exc_value == Py_None) {
return PyObject_CallNoArgs(_exception); return PyObject_CallNoArgs(_exception);
} else if (PyTuple_Check(_exc_value)) { }
else if (PyTuple_Check(_exc_value)) {
return PyObject_Call(_exception, _exc_value, nullptr); return PyObject_Call(_exception, _exc_value, nullptr);
} else { }
else {
return PyObject_CallOneArg(_exception, _exc_value); return PyObject_CallOneArg(_exception, _exc_value);
} }
}*/ }*/
@ -362,8 +353,7 @@ __getattribute__(PyObject *self, PyObject *attr) const {
if (item != nullptr) { if (item != nullptr) {
// PyDict_GetItem returns a borrowed reference. // PyDict_GetItem returns a borrowed reference.
Py_INCREF(item); return Py_NewRef(item);
return item;
} }
return PyObject_GenericGetAttr(self, attr); return PyObject_GenericGetAttr(self, attr);
@ -624,7 +614,7 @@ do_python_task() {
if (result == nullptr) { if (result == nullptr) {
result = Py_None; result = Py_None;
} }
Py_INCREF(result); result = Py_NewRef(result);
Py_DECREF(exc); Py_DECREF(exc);
#else #else
if (_PyGen_FetchStopIterationValue(&result) == 0) { if (_PyGen_FetchStopIterationValue(&result) == 0) {

View File

@ -47,10 +47,10 @@ __reduce__() const {
} }
extern struct Dtool_PyTypedObject Dtool_Datagram; extern struct Dtool_PyTypedObject Dtool_Datagram;
Py_INCREF((PyObject *)&Dtool_Datagram._PyType); PyObject *tp = (PyObject *)&Dtool_Datagram._PyType;
PyObject *result = PyTuple_New(2); 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); PyTuple_SET_ITEM(result, 1, args);
return result; return result;
} }

View File

@ -304,10 +304,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
return -1; return -1;
} }
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
view->len = this->_this->size() * sizeof(Element); view->len = this->_this->size() * sizeof(Element);
view->readonly = 0; view->readonly = 0;
@ -345,10 +342,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
template<> template<>
INLINE int Extension<PointerToArray<LMatrix3f> >:: INLINE int Extension<PointerToArray<LMatrix3f> >::
__getbuffer__(PyObject *self, Py_buffer *view, int flags) { __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
set_matrix_view(*view, flags, this->_this->size(), 3, false, false); set_matrix_view(*view, flags, this->_this->size(), 3, false, false);
@ -367,10 +361,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
template<> template<>
INLINE int Extension<PointerToArray<LMatrix3d> >:: INLINE int Extension<PointerToArray<LMatrix3d> >::
__getbuffer__(PyObject *self, Py_buffer *view, int flags) { __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
set_matrix_view(*view, flags, this->_this->size(), 3, true, false); set_matrix_view(*view, flags, this->_this->size(), 3, true, false);
@ -389,10 +380,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
template<> template<>
INLINE int Extension<PointerToArray<UnalignedLMatrix4f> >:: INLINE int Extension<PointerToArray<UnalignedLMatrix4f> >::
__getbuffer__(PyObject *self, Py_buffer *view, int flags) { __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
set_matrix_view(*view, flags, this->_this->size(), 4, false, false); set_matrix_view(*view, flags, this->_this->size(), 4, false, false);
@ -411,10 +399,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
template<> template<>
INLINE int Extension<PointerToArray<UnalignedLMatrix4d> >:: INLINE int Extension<PointerToArray<UnalignedLMatrix4d> >::
__getbuffer__(PyObject *self, Py_buffer *view, int flags) { __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
set_matrix_view(*view, flags, this->_this->size(), 4, true, false); 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; return -1;
} }
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
view->len = this->_this->size() * sizeof(Element); view->len = this->_this->size() * sizeof(Element);
view->readonly = 1; view->readonly = 1;
@ -518,10 +500,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const {
"Object is not writable."); "Object is not writable.");
return -1; return -1;
} }
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
set_matrix_view(*view, flags, this->_this->size(), 3, false, true); 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."); "Object is not writable.");
return -1; return -1;
} }
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
set_matrix_view(*view, flags, this->_this->size(), 3, true, true); 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."); "Object is not writable.");
return -1; return -1;
} }
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
set_matrix_view(*view, flags, this->_this->size(), 4, false, true); 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."); "Object is not writable.");
return -1; return -1;
} }
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) this->_this->p(); view->buf = (void*) this->_this->p();
set_matrix_view(*view, flags, this->_this->size(), 4, true, true); set_matrix_view(*view, flags, this->_this->size(), 4, true, true);

View File

@ -53,10 +53,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) {
view->internal = (void*) data; view->internal = (void*) data;
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) handle->get_write_pointer(); view->buf = (void*) handle->get_write_pointer();
view->len = row_size * handle->get_num_rows(); view->len = row_size * handle->get_num_rows();
view->readonly = 0; view->readonly = 0;
@ -115,10 +112,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const {
view->internal = (void*) data; view->internal = (void*) data;
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void*) handle->get_read_pointer(true); view->buf = (void*) handle->get_read_pointer(true);
view->len = row_size * handle->get_num_rows(); view->len = row_size * handle->get_num_rows();
view->readonly = 1; view->readonly = 1;

View File

@ -78,9 +78,7 @@ init(PyObject *tex_filter) {
return false; return false;
} }
_entry_point = tex_filter; _entry_point = Py_NewRef(tex_filter);
Py_INCREF(_entry_point);
return true; return true;
} }

View File

@ -265,8 +265,7 @@ __ifloordiv__(PyObject *self, FLOATTYPE scalar) {
_this->_v(0) = std::floor(_this->_v(0) / scalar); _this->_v(0) = std::floor(_this->_v(0) / scalar);
_this->_v(1) = std::floor(_this->_v(1) / scalar); _this->_v(1) = std::floor(_this->_v(1) / scalar);
#endif #endif
Py_INCREF(self); return Py_NewRef(self);
return self;
} }
/** /**
@ -295,8 +294,7 @@ INLINE_LINMATH PyObject *Extension<FLOATNAME(LVecBase2)>::
__ipow__(PyObject *self, FLOATTYPE exponent) { __ipow__(PyObject *self, FLOATTYPE exponent) {
_this->_v(0) = cpow(_this->_v(0), exponent); _this->_v(0) = cpow(_this->_v(0), exponent);
_this->_v(1) = cpow(_this->_v(1), exponent); _this->_v(1) = cpow(_this->_v(1), exponent);
Py_INCREF(self); return Py_NewRef(self);
return self;
} }
/** /**
@ -371,10 +369,8 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const {
static const char format[2] = {FLOATTOKEN, 0}; static const char format[2] = {FLOATTOKEN, 0};
static const Py_ssize_t shape = FLOATNAME(LVecBase2)::num_components; static const Py_ssize_t shape = FLOATNAME(LVecBase2)::num_components;
Py_INCREF(self);
view->buf = (void *)_this->get_data(); view->buf = (void *)_this->get_data();
view->obj = self; view->obj = Py_NewRef(self);
view->len = 2 * sizeof(FLOATTYPE); view->len = 2 * sizeof(FLOATTYPE);
view->readonly = 1; view->readonly = 1;
view->itemsize = sizeof(FLOATTYPE); view->itemsize = sizeof(FLOATTYPE);

View File

@ -274,8 +274,7 @@ __ifloordiv__(PyObject *self, FLOATTYPE scalar) {
_this->_v(1) = std::floor(_this->_v(1) / scalar); _this->_v(1) = std::floor(_this->_v(1) / scalar);
_this->_v(2) = std::floor(_this->_v(2) / scalar); _this->_v(2) = std::floor(_this->_v(2) / scalar);
#endif #endif
Py_INCREF(self); return Py_NewRef(self);
return self;
} }
/** /**
@ -306,8 +305,7 @@ __ipow__(PyObject *self, FLOATTYPE exponent) {
_this->_v(0) = cpow(_this->_v(0), exponent); _this->_v(0) = cpow(_this->_v(0), exponent);
_this->_v(1) = cpow(_this->_v(1), exponent); _this->_v(1) = cpow(_this->_v(1), exponent);
_this->_v(2) = cpow(_this->_v(2), exponent); _this->_v(2) = cpow(_this->_v(2), exponent);
Py_INCREF(self); return Py_NewRef(self);
return self;
} }
/** /**
@ -384,10 +382,8 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const {
static const char format[2] = {FLOATTOKEN, 0}; static const char format[2] = {FLOATTOKEN, 0};
static const Py_ssize_t shape = FLOATNAME(LVecBase3)::num_components; static const Py_ssize_t shape = FLOATNAME(LVecBase3)::num_components;
Py_INCREF(self);
view->buf = (void *)_this->get_data(); view->buf = (void *)_this->get_data();
view->obj = self; view->obj = Py_NewRef(self);
view->len = 3 * sizeof(FLOATTYPE); view->len = 3 * sizeof(FLOATTYPE);
view->readonly = 1; view->readonly = 1;
view->itemsize = sizeof(FLOATTYPE); view->itemsize = sizeof(FLOATTYPE);

View File

@ -287,8 +287,7 @@ __ifloordiv__(PyObject *self, FLOATTYPE scalar) {
_this->_v(2) = std::floor(_this->_v(2) / scalar); _this->_v(2) = std::floor(_this->_v(2) / scalar);
_this->_v(3) = std::floor(_this->_v(3) / scalar); _this->_v(3) = std::floor(_this->_v(3) / scalar);
#endif #endif
Py_INCREF(self); return Py_NewRef(self);
return self;
} }
/** /**
@ -321,8 +320,7 @@ __ipow__(PyObject *self, FLOATTYPE exponent) {
_this->_v(1) = cpow(_this->_v(1), exponent); _this->_v(1) = cpow(_this->_v(1), exponent);
_this->_v(2) = cpow(_this->_v(2), exponent); _this->_v(2) = cpow(_this->_v(2), exponent);
_this->_v(3) = cpow(_this->_v(3), exponent); _this->_v(3) = cpow(_this->_v(3), exponent);
Py_INCREF(self); return Py_NewRef(self);
return self;
} }
/** /**
@ -402,10 +400,8 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const {
static const char format[2] = {FLOATTOKEN, 0}; static const char format[2] = {FLOATTOKEN, 0};
static const Py_ssize_t shape = FLOATNAME(LVecBase4)::num_components; static const Py_ssize_t shape = FLOATNAME(LVecBase4)::num_components;
Py_INCREF(self);
view->buf = (void *)_this->get_data(); view->buf = (void *)_this->get_data();
view->obj = self; view->obj = Py_NewRef(self);
view->len = 4 * sizeof(FLOATTYPE); view->len = 4 * sizeof(FLOATTYPE);
view->readonly = 1; view->readonly = 1;
view->itemsize = sizeof(FLOATTYPE); view->itemsize = sizeof(FLOATTYPE);

View File

@ -22,8 +22,7 @@ get_data() const {
if (data == nullptr) { if (data == nullptr) {
data = Py_None; data = Py_None;
} }
Py_INCREF(data); return Py_NewRef(data);
return data;
} }
/** /**

View File

@ -25,8 +25,7 @@ set_data(PyObject *data) {
void *old_data = _this->get_data(); void *old_data = _this->get_data();
if (data != nullptr && data != Py_None) { if (data != nullptr && data != Py_None) {
Py_INCREF(data); _this->set_data((void *)Py_NewRef(data));
_this->set_data((void *)data);
_this->_destroy_callback = &destroy_callback; _this->_destroy_callback = &destroy_callback;
} else { } else {
_this->set_data(nullptr); _this->set_data(nullptr);

View File

@ -82,10 +82,9 @@ collide(PyObject* arg, PyObject* callback) {
return -1; return -1;
} else { } else {
_python_callback = (PyObject*) callback; _python_callback = Py_NewRef(callback);
Py_XINCREF(_python_callback);
dSpaceCollide(_this->get_id(), (void*) arg, &near_callback); dSpaceCollide(_this->get_id(), (void*) arg, &near_callback);
Py_XDECREF(_python_callback); Py_CLEAR(_python_callback);
return 0; return 0;
} }
} }

View File

@ -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); PyErr_Format(PyExc_TypeError, "'%s' object is not callable", callback->ob_type->tp_name);
return -1; return -1;
} else { } else {
_python_callback = (PyObject*) callback; _python_callback = Py_XNewRef(callback);
Py_XINCREF(_python_callback);
dSpaceCollide2(geom1.get_id(), geom2.get_id(), (void*) arg, &near_callback); dSpaceCollide2(geom1.get_id(), geom2.get_id(), (void*) arg, &near_callback);
Py_XDECREF(_python_callback); Py_CLEAR(_python_callback);
return 0; return 0;
} }
} }

View File

@ -110,10 +110,9 @@ get_tight_bounds() const {
PyObject *max_inst = DTool_CreatePyInstance((void*) max_point, Dtool_LPoint3f, true, false); PyObject *max_inst = DTool_CreatePyInstance((void*) max_point, Dtool_LPoint3f, true, false);
#endif #endif
return Py_BuildValue("NN", min_inst, max_inst); return Py_BuildValue("NN", min_inst, max_inst);
}
} else { else {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
} }

View File

@ -23,8 +23,7 @@ INLINE PyObject *Extension<NodePath>::
get_python_tags() { get_python_tags() {
// An empty NodePath returns None // An empty NodePath returns None
if (_this->is_empty()) { if (_this->is_empty()) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
return invoke_extension(_this->node()).get_python_tags(); return invoke_extension(_this->node()).get_python_tags();
} }
@ -38,8 +37,7 @@ INLINE PyObject *Extension<NodePath>::
get_tag_keys() const { get_tag_keys() const {
// An empty NodePath returns None // An empty NodePath returns None
if (_this->is_empty()) { if (_this->is_empty()) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
return invoke_extension(_this->node()).get_tag_keys(); return invoke_extension(_this->node()).get_tag_keys();
} }
@ -52,8 +50,7 @@ INLINE PyObject *Extension<NodePath>::
get_python_tag_keys() const { get_python_tag_keys() const {
// An empty NodePath returns None // An empty NodePath returns None
if (_this->is_empty()) { if (_this->is_empty()) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
return invoke_extension(_this->node()).get_python_tag_keys(); 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 // An empty NodePath quietly returns no tags. This makes
// get_net_python_tag() easier to implement. // get_net_python_tag() easier to implement.
if (_this->is_empty()) { if (_this->is_empty()) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
return invoke_extension(_this->node()).get_python_tag(key); return invoke_extension(_this->node()).get_python_tag(key);
} }

View File

@ -59,8 +59,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const {
PyObject *dupe = PyDict_GetItem(memo, self); PyObject *dupe = PyDict_GetItem(memo, self);
if (dupe != nullptr) { if (dupe != nullptr) {
// Already in the memo dictionary. // Already in the memo dictionary.
Py_INCREF(dupe); return Py_NewRef(dupe);
return dupe;
} }
NodePath *np_dupe; NodePath *np_dupe;
@ -174,8 +173,7 @@ PyObject *Extension<NodePath>::
get_tags() const { get_tags() const {
// An empty NodePath returns None // An empty NodePath returns None
if (_this->is_empty()) { if (_this->is_empty()) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
// Just call PandaNode.tags rather than defining a whole new interface. // 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); return Py_BuildValue("NN", min_inst, max_inst);
} else { } else {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
} }

View File

@ -50,8 +50,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const {
PyObject *dupe = PyDict_GetItem(memo, self); PyObject *dupe = PyDict_GetItem(memo, self);
if (dupe != nullptr) { if (dupe != nullptr) {
// Already in the memo dictionary. // Already in the memo dictionary.
Py_INCREF(dupe); return Py_NewRef(dupe);
return dupe;
} }
PT(PandaNode) node_dupe = _this->copy_subgraph(); PT(PandaNode) node_dupe = _this->copy_subgraph();
@ -94,9 +93,7 @@ get_tag_keys() const {
*/ */
PyObject *Extension<PandaNode>:: PyObject *Extension<PandaNode>::
get_python_tags() { get_python_tags() {
PyObject *dict = do_get_python_tags(); return Py_NewRef(do_get_python_tags());
Py_INCREF(dict);
return dict;
} }
/** /**
@ -121,8 +118,7 @@ set_python_tag(PyObject *key, PyObject *value) {
PyObject *Extension<PandaNode>:: PyObject *Extension<PandaNode>::
get_python_tag(PyObject *key) const { get_python_tag(PyObject *key) const {
if (_this->_python_tag_data == nullptr) { if (_this->_python_tag_data == nullptr) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
PyObject *dict = ((PythonTagDataImpl *)_this->_python_tag_data.p())->_dict; PyObject *dict = ((PythonTagDataImpl *)_this->_python_tag_data.p())->_dict;
@ -131,8 +127,7 @@ get_python_tag(PyObject *key) const {
value = Py_None; value = Py_None;
} }
// PyDict_GetItem returns a borrowed reference. // PyDict_GetItem returns a borrowed reference.
Py_INCREF(value); return Py_NewRef(value);
return value;
} }
/** /**

View File

@ -44,10 +44,9 @@ PythonLoaderFileType() {
PythonLoaderFileType:: PythonLoaderFileType::
PythonLoaderFileType(std::string extension, PyObject *entry_point) : PythonLoaderFileType(std::string extension, PyObject *entry_point) :
_extension(std::move(extension)), _extension(std::move(extension)),
_entry_point(entry_point) { _entry_point(Py_NewRef(entry_point)) {
init_type(); init_type();
Py_INCREF(entry_point);
} }
/** /**
@ -314,8 +313,7 @@ load_file(const Filename &path, const LoaderOptions &options,
record->ref(); record->ref();
PyTuple_SET_ITEM(args, 2, DTool_CreatePyInstanceTyped((void *)record, Dtool_BamCacheRecord, true, false, record->get_type_index())); PyTuple_SET_ITEM(args, 2, DTool_CreatePyInstanceTyped((void *)record, Dtool_BamCacheRecord, true, false, record->get_type_index()));
} else { } else {
PyTuple_SET_ITEM(args, 2, Py_None); PyTuple_SET_ITEM(args, 2, Py_NewRef(Py_None));
Py_INCREF(Py_None);
} }
PT(PandaNode) node; PT(PandaNode) node;

View File

@ -96,8 +96,7 @@ get_composition_cache() const {
PyObject *a, *b; PyObject *a, *b;
const RenderState *source = _this->_composition_cache.get_key(i); const RenderState *source = _this->_composition_cache.get_key(i);
if (source == nullptr) { if (source == nullptr) {
a = Py_None; a = Py_NewRef(Py_None);
Py_INCREF(a);
} else { } else {
source->ref(); source->ref();
a = DTool_CreatePyInstanceTyped((void *)source, Dtool_RenderState, 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; const RenderState *result = _this->_composition_cache.get_data(i)._result;
if (result == nullptr) { if (result == nullptr) {
b = Py_None; b = Py_NewRef(Py_None);
Py_INCREF(b);
} else { } else {
result->ref(); result->ref();
b = DTool_CreatePyInstanceTyped((void *)result, Dtool_RenderState, b = DTool_CreatePyInstanceTyped((void *)result, Dtool_RenderState,
@ -144,8 +142,7 @@ get_invert_composition_cache() const {
PyObject *a, *b; PyObject *a, *b;
const RenderState *source = _this->_invert_composition_cache.get_key(i); const RenderState *source = _this->_invert_composition_cache.get_key(i);
if (source == nullptr) { if (source == nullptr) {
a = Py_None; a = Py_NewRef(Py_None);
Py_INCREF(a);
} else { } else {
source->ref(); source->ref();
a = DTool_CreatePyInstanceTyped((void *)source, Dtool_RenderState, 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; const RenderState *result = _this->_invert_composition_cache.get_data(i)._result;
if (result == nullptr) { if (result == nullptr) {
b = Py_None; b = Py_NewRef(Py_None);
Py_INCREF(b);
} else { } else {
result->ref(); result->ref();
b = DTool_CreatePyInstanceTyped((void *)result, Dtool_RenderState, b = DTool_CreatePyInstanceTyped((void *)result, Dtool_RenderState,

View File

@ -42,8 +42,7 @@ get_composition_cache() const {
const TransformState *source = _this->_composition_cache.get_key(si); const TransformState *source = _this->_composition_cache.get_key(si);
if (source == nullptr) { if (source == nullptr) {
a = Py_None; a = Py_NewRef(Py_None);
Py_INCREF(a);
} else { } else {
source->ref(); source->ref();
a = DTool_CreatePyInstanceTyped((void *)source, Dtool_TransformState, 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; const TransformState *result = _this->_composition_cache.get_data(si)._result;
if (result == nullptr) { if (result == nullptr) {
b = Py_None; b = Py_NewRef(Py_None);
Py_INCREF(b);
} else { } else {
result->ref(); result->ref();
b = DTool_CreatePyInstanceTyped((void *)result, Dtool_TransformState, 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); const TransformState *source = _this->_invert_composition_cache.get_key(si);
if (source == nullptr) { if (source == nullptr) {
a = Py_None; a = Py_NewRef(Py_None);
Py_INCREF(a);
} else { } else {
source->ref(); source->ref();
a = DTool_CreatePyInstanceTyped((void *)source, Dtool_TransformState, 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; const TransformState *result = _this->_invert_composition_cache.get_data(si)._result;
if (result == nullptr) { if (result == nullptr) {
b = Py_None; b = Py_NewRef(Py_None);
Py_INCREF(b);
} else { } else {
result->ref(); result->ref();
b = DTool_CreatePyInstanceTyped((void *)result, Dtool_TransformState, b = DTool_CreatePyInstanceTyped((void *)result, Dtool_TransformState,

View File

@ -27,8 +27,7 @@ PythonThread(PyObject *function, PyObject *args,
const std::string &name, const std::string &sync_name) : const std::string &name, const std::string &sync_name) :
Thread(name, sync_name) Thread(name, sync_name)
{ {
_function = function; _function = Py_NewRef(function);
Py_INCREF(_function);
_args = nullptr; _args = nullptr;
_result = nullptr; _result = nullptr;
@ -78,14 +77,13 @@ PyObject *PythonThread::
join() { join() {
Thread::join(); Thread::join();
if (_result == nullptr) { PyObject *result = _result;
if (result == nullptr) {
// No result; return None. // No result; return None.
Py_INCREF(Py_None); result = Py_None;
return Py_None;
} }
Py_INCREF(_result); return Py_NewRef(result);
return _result;
} }
/** /**
@ -147,10 +145,7 @@ call_python_func(PyObject *function, PyObject *args) {
PyObject *exc, *val, *tb; PyObject *exc, *val, *tb;
PyErr_Fetch(&exc, &val, &tb); PyErr_Fetch(&exc, &val, &tb);
Py_XINCREF(exc); PyErr_Restore(Py_XNewRef(exc), Py_XNewRef(val), Py_XNewRef(tb));
Py_XINCREF(val);
Py_XINCREF(tb);
PyErr_Restore(exc, val, tb);
PyErr_Print(); PyErr_Print();
PyErr_Restore(exc, val, tb); 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 // Temporarily restore the exception state so we can print a callback
// on-the-spot. // on-the-spot.
Py_XINCREF(exc); PyErr_Restore(Py_XNewRef(exc), Py_XNewRef(val), Py_XNewRef(tb));
Py_XINCREF(val);
Py_XINCREF(tb);
PyErr_Restore(exc, val, tb);
PyErr_Print(); PyErr_Print();
PyThreadState_Swap(orig_thread_state); PyThreadState_Swap(orig_thread_state);
@ -252,10 +244,7 @@ call_python_func(PyObject *function, PyObject *args) {
thread_cat.error() thread_cat.error()
<< "Exception occurred within " << *current_thread << "\n"; << "Exception occurred within " << *current_thread << "\n";
Py_XINCREF(exc); PyErr_Restore(Py_XNewRef(exc), Py_XNewRef(val), Py_XNewRef(tb));
Py_XINCREF(val);
Py_XINCREF(tb);
PyErr_Restore(exc, val, tb);
PyErr_Print(); PyErr_Print();
} else { } else {
thread_cat.info() thread_cat.info()

View File

@ -63,8 +63,7 @@ get_points() const {
default: default:
Py_DECREF(list); Py_DECREF(list);
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
return list; return list;
@ -92,10 +91,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const {
int channels = _this->get_num_channels(); int channels = _this->get_num_channels();
int num_pixels = _this->get_x_size() * _this->get_y_size(); int num_pixels = _this->get_x_size() * _this->get_y_size();
if (self != nullptr) { view->obj = Py_XNewRef(self);
Py_INCREF(self);
}
view->obj = self;
view->buf = (void *) &(table[0]); view->buf = (void *) &(table[0]);
view->len = 4 * table.size(); view->len = 4 * table.size();
view->readonly = 1; view->readonly = 1;

View File

@ -107,7 +107,7 @@ make_python_frame_collector(PyFrameObject *frame, PyCodeObject *code) {
} }
meth_name = PyUnicode_FromFormat("_%s%S", cls_name, meth_name); meth_name = PyUnicode_FromFormat("_%s%S", cls_name, meth_name);
} else { } else {
Py_INCREF(meth_name); meth_name = Py_NewRef(meth_name);
} }
if (!find_method(cls, meth_name, code)) { if (!find_method(cls, meth_name, code)) {
// Not a matching method object, it's something else. Forget it. // Not a matching method object, it's something else. Forget it.

View File

@ -135,8 +135,7 @@ read_object() {
} }
if (ptr == nullptr) { if (ptr == nullptr) {
Py_INCREF(Py_None); return Py_NewRef(Py_None);
return Py_None;
} }
if (ref_ptr != nullptr) { if (ref_ptr != nullptr) {
@ -165,15 +164,13 @@ get_file_version() const {
*/ */
void Extension<BamReader>:: void Extension<BamReader>::
register_factory(TypeHandle handle, PyObject *func) { register_factory(TypeHandle handle, PyObject *func) {
nassertv(func != nullptr);
if (!PyCallable_Check(func)) { if (!PyCallable_Check(func)) {
Dtool_Raise_TypeError("second argument to register_factory must be callable"); Dtool_Raise_TypeError("second argument to register_factory must be callable");
return; return;
} }
Py_INCREF(func); void *user_data = (void *)Py_NewRef(func);
BamReader::get_factory()->register_factory(handle, &factory_callback, (void *)func); BamReader::get_factory()->register_factory(handle, &factory_callback, user_data);
} }
#endif #endif

View File

@ -17,8 +17,7 @@
* Increments the reference count. Assumes the GIL is held. * Increments the reference count. Assumes the GIL is held.
*/ */
INLINE ParamPyObject:: INLINE ParamPyObject::
ParamPyObject(PyObject *value) : _value(value) { ParamPyObject(PyObject *value) : _value(Py_NewRef(value)) {
Py_INCREF(value);
} }
/** /**
@ -26,6 +25,5 @@ ParamPyObject(PyObject *value) : _value(value) {
*/ */
INLINE PyObject *ParamPyObject:: INLINE PyObject *ParamPyObject::
get_value() const { get_value() const {
Py_INCREF(_value); return Py_NewRef(_value);
return _value;
} }

View File

@ -37,8 +37,7 @@ extern struct Dtool_PyTypedObject Dtool_PythonCallbackObject;
*/ */
PythonCallbackObject:: PythonCallbackObject::
PythonCallbackObject(PyObject *function) { PythonCallbackObject(PyObject *function) {
_function = Py_None; _function = Py_NewRef(Py_None);
Py_INCREF(_function);
set_function(function); set_function(function);
@ -69,8 +68,7 @@ PythonCallbackObject::
void PythonCallbackObject:: void PythonCallbackObject::
set_function(PyObject *function) { set_function(PyObject *function) {
Py_DECREF(_function); Py_DECREF(_function);
_function = function; _function = Py_NewRef(function);
Py_INCREF(_function);
if (_function != Py_None && !PyCallable_Check(_function)) { if (_function != Py_None && !PyCallable_Check(_function)) {
nassert_raise("Invalid function passed to PythonCallbackObject"); nassert_raise("Invalid function passed to PythonCallbackObject");
} }
@ -81,8 +79,7 @@ set_function(PyObject *function) {
*/ */
PyObject *PythonCallbackObject:: PyObject *PythonCallbackObject::
get_function() { get_function() {
Py_INCREF(_function); return Py_NewRef(_function);
return _function;
} }
/** /**
@ -90,7 +87,7 @@ get_function() {
*/ */
PyObject *PythonCallbackObject:: PyObject *PythonCallbackObject::
__reduce__() const { __reduce__() const {
return Py_BuildValue("O(O)", (PyObject *)&Dtool_PythonCallbackObject, _function); return Py_BuildValue("O(O)", (PyObject *)&Dtool_PythonCallbackObject._PyType, _function);
} }
/** /**

View File

@ -149,8 +149,7 @@ wrap_typed_writable(void *from_this, PyTypeObject *from_type) {
} }
nassertr(to_this->_self != nullptr, nullptr); nassertr(to_this->_self != nullptr, nullptr);
Py_INCREF(to_this->_self); return Py_NewRef(to_this->_self);
return to_this->_self;
} }
/** /**
@ -212,8 +211,8 @@ __new__(PyTypeObject *cls) {
// Make sure that the bindings know how to obtain a wrapper for this type. // Make sure that the bindings know how to obtain a wrapper for this type.
TypeRegistry *registry = TypeRegistry::ptr(); TypeRegistry *registry = TypeRegistry::ptr();
registry->record_python_type(*handle, cls, &wrap_typed_writable); PyTypeObject *cls_ref = (PyTypeObject *)Py_NewRef((PyObject *)cls);
Py_INCREF(cls); registry->record_python_type(*handle, cls_ref, &wrap_typed_writable);
// Note that we don't increment the reference count here, because that would // Note that we don't increment the reference count here, because that would
// create a memory leak. The TypedWritableProxy gets deleted when the Python // create a memory leak. The TypedWritableProxy gets deleted when the Python

View File

@ -28,11 +28,9 @@ _py_write(PyObject *self, PyObject *args) {
char *text; char *text;
if (PyArg_ParseTuple(args, "iss", &prio, &tag, &text)) { if (PyArg_ParseTuple(args, "iss", &prio, &tag, &text)) {
__android_log_write(prio, tag, text); __android_log_write(prio, tag, text);
Py_INCREF(Py_None); Py_RETURN_NONE;
return Py_None;
} }
return NULL; return NULL;
} }
static PyMethodDef python_simple_funcs[] = { static PyMethodDef python_simple_funcs[] = {