[Python-ideas] Implicit submodule imports

Antoine Pitrou solipsis at pitrou.net
Fri Sep 26 13:32:23 CEST 2014


On Fri, 26 Sep 2014 02:02:01 +0100
Nathaniel Smith <njs at pobox.com> wrote:
> 
> This code has been around forever, but I don't know why. AFAIK we
> could replace the above with
> 
>     if (compatible_for_assignment(oldto, newto, "__class__")) {
>         if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE) {
>             Py_INCREF(newto);
>         }
>         Py_TYPE(self) = newto;
>         if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE) {
>            Py_DECREF(oldto);
>         }
>         return 0;
>     }
> 
> and everything would just work, but I could well be missing something?
> Is there some dragon lurking inside Python's memory management or is
> this just an ancient overabundance of caution?

The tp_dealloc for a heap type is not the same as the non-heap base
type's tp_dealloc. See subtype_dealloc() in typeobject.c. Switching the
__class__ would deallocate the instance with an incompatible tp_dealloc.

(in particular, a heap type is always incref'ed when an instance is
created and decref'ed when an instance is destroyed, but the base type
wouldn't)

Also, look at compatible_for_assignment(): it calls same_slots_added()
which assumes both args are heap types.


Note that this can be a gotcha when using the stable ABI:
http://bugs.python.org/issue16690

Regards

Antoine.




More information about the Python-ideas mailing list