◐ Shell
clean mode source ↗

bpo-43973: Use Py_TPFLAGS_IMMUTABLETYPE to check for class assignments by erlend-aasland · Pull Request #25714 · python/cpython

@erlend-aasland erlend-aasland changed the title Use Py_TPFLAGS_IMMUTABLETYPE to check for class assignments bpo-43973: Use Py_TPFLAGS_IMMUTABLETYPE to check for class assignments

Apr 29, 2021

@erlend-aasland

cc. @vstinner

See msg392291: Can we get rid of the huge comment preceding the if statement now? Or at least reduce it considerably.

@erlend-aasland

AFAICS, this does not require a news item, but I might be wrong.

@shreyanavigyan

Doesn't this also require a change?

if (compatible_for_assignment(oldto, newto, "__class__")) {
if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Py_INCREF(newto);
}
Py_SET_TYPE(self, newto);
if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
Py_DECREF(oldto);
return 0;
}
else {
return -1;
}

Suggested :-

 if (compatible_for_assignment(oldto, newto, "__class__")) { 
     if (!(newto->tp_flags & Py_TPFLAGS_IMMUTABLETYPE)) { 
         Py_INCREF(newto); 
     } 
     Py_SET_TYPE(self, newto); 
     if (!(oldto->tp_flags & Py_TPFLAGS_IMMUTABLETYPE))
         Py_DECREF(oldto); 
     return 0; 
 } 
 else { 
     return -1; 
 } 

@erlend-aasland

Doesn't this also require a change?

AFAICT, no. They adjust the ref. count if heap types are used:

If the old class was a heap type, decrement its ref. count. If the new class is a heap type, acquire a strong reference to it (increment the ref. count).

vstinner

@erlend-aasland

@vstinner

Merged, thanks for the fix.

@pitrou

The comment above the check should have been fixed to reflect the new semantics, no?

Also, is the explicit check for PyModule_Type still needed?

@erlend-aasland

The comment above the check should have been fixed to reflect the new semantics, no?

Yes, and I believe it can be considerably reduced.

Also, is the explicit check for PyModule_Type still needed?

I don't know. See bpo-24912.