To clarify how Python handles two equal objects

Mark Bourne nntp.mbourne at spamgourmet.com
Sun Jan 15 08:14:50 EST 2023


Jen Kris wrote:
> Avi,
> 
> Your comments go farther afield than my original question, but you made some interesting additional points.  For example, I sometimes work with the C API and sys.getrefcount may be helpful in deciding when to INCREF and DECREF.  But that’s another issue.
> 
> The situation I described in my original post is limited to a case such as x = y where both "x" and "y" are arrays – whether they are lists in Python, or from the array module – and the question in a compiled C extension is whether the assignment can be done simply by "x" taking the pointer to "y" rather than moving all the data from "y" into the memory buffer for "x" which, for a wide array, would be much more time consuming than just moving a pointer.  The other advantage to doing it that way is if, as in my case, we perform a math operation on any element in "x" then Python expects that the same change to be reflected in "y."  If I don’t use the same pointers then I would have to perform that operation twice – once for "x" and once  for "y" – in addition to the expense of moving all the data.
> 
> The answers I got from this post confirmed that it I can use the pointer if "y" is not re-defined to something else during the lifespan of "x."  If it is then "x" has to be restored to its original pointer.  I did it that way, and helpfully the compiler did not overrule me.

I haven't done much with C extensions, but I don't think you'd need to 
do anything with "x" in that case.  If something else is assigned to 
"y", "x" would still be a reference to the original object - why would 
it need to be "restored" to anything?  Unless I've misunderstood what's 
going on here...

-- 
Mark.


More information about the Python-list mailing list