Replace PyObject_GetAttrString with direct type references

Replace ~230 occurrences of PyObject_GetAttrString(McRFPy_API::mcrf_module, "TypeName")
with direct &mcrfpydef::PyXxxType references across 32 source files.

Each PyObject_GetAttrString call returns a new reference. When used inline
in PyObject_IsInstance(), that reference was immediately leaked. When used
for tp_alloc, the reference required careful Py_DECREF management that was
often missing on error paths.

Direct type references are compile-time constants that never need reference
counting, eliminating ~230 potential leak sites and removing ~100 lines of
Py_DECREF/Py_XDECREF cleanup code.

Also adds extractDrawable() helper in UICollection.cpp to replace repeated
8-way type-check-and-extract chains with a single function call.

Closes #267, closes #268

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
John McCardle 2026-03-07 23:18:42 -05:00
commit 71eb01c950
32 changed files with 249 additions and 944 deletions

View file

@ -255,7 +255,7 @@ int UICaption::set_color_member(PyUICaptionObject* self, PyObject* value, void*
auto member_ptr = reinterpret_cast<intptr_t>(closure);
//TODO: this logic of (PyColor instance OR tuple -> sf::color) should be encapsulated for reuse
int r, g, b, a;
if (PyObject_IsInstance(value, PyObject_GetAttrString(McRFPy_API::mcrf_module, "Color") /*(PyObject*)&mcrfpydef::PyColorType)*/))
if (PyObject_IsInstance(value, (PyObject*)&mcrfpydef::PyColorType))
{
// get value from mcrfpy.Color instance
auto c = ((PyColorObject*)value)->data;
@ -479,7 +479,7 @@ int UICaption::init(PyUICaptionObject* self, PyObject* args, PyObject* kwds)
// Handle font argument
std::shared_ptr<PyFont> pyfont = nullptr;
if (font && font != Py_None) {
if (!PyObject_IsInstance(font, PyObject_GetAttrString(McRFPy_API::mcrf_module, "Font"))) {
if (!PyObject_IsInstance(font, (PyObject*)&mcrfpydef::PyFontType)) {
PyErr_SetString(PyExc_TypeError, "font must be a mcrfpy.Font instance");
return -1;
}
@ -571,11 +571,7 @@ int UICaption::init(PyUICaptionObject* self, PyObject* args, PyObject* kwds)
}
// #184: Check if this is a Python subclass (for callback method support)
PyObject* caption_type = PyObject_GetAttrString(McRFPy_API::mcrf_module, "Caption");
if (caption_type) {
self->data->is_python_subclass = (PyObject*)Py_TYPE(self) != caption_type;
Py_DECREF(caption_type);
}
self->data->is_python_subclass = (PyObject*)Py_TYPE(self) != (PyObject*)&mcrfpydef::PyUICaptionType;
return 0;
}