To clarify how Python handles two equal objects

Peter J. Holzer hjp-python at hjp.at
Fri Jan 13 14:38:49 EST 2023


On 2023-01-13 16:57:45 +0100, Jen Kris via Python-list wrote:
> Thanks for your comments.  You make a good point. 
> 
> Going back to my original question, and using your slice() example: 
> 
> middle_by_two = slice(5, 10, 2)
> nums = [n for n in range(12)]
> q = nums[middle_by_two]
> x = id(q)
> b = q
> y = id(b)
> 
> If I assign "b" to "q",

You don't asssign b to q. You assign q to b. Assignment is not
commutative, the direction matters.

> then x and y match – they point to the same memory until "b" OR "q"
> are  reassigned to something else.

Correct.

>  If "q" changes during the lifetime of "b" then it’s not safe to use
>the pointer to "q" for "b", as in:

There is no pointer to q[1]. q is a pointer to something (an object of type
list with 3 elements).

b is a pointer to the same object at this point. Of course, if you
assign a different pointer to q, then q will point to the new object
from that point on while b will continue to point to the original object
(until it is also re-assigned).

> nums = [n for n in range(2, 14)]
> q = nums[middle_by_two]
> x = id(q)
> y = id(b)
> 
> Now "x" and "y" are different, as we would expect.
> So when writing a spot speed up in a compiled language,

If you are writing a Python compiler you certainly will have to adjust
for the fact that the same variable may hold pointers to very different
objects over its lifetime. But as far as I understand it, you aren't
trying to write a Python compiler, just an extension, so that shouldn't
concern you.

> The motivation behind my question was that in a compiled extension
> it’s faster to borrow a pointer than to move an entire array if it’s
> possible, but special care must be taken. 

I still don't understand what you mean by that.

        hp

[1] Not quite true. The run-time system must keep track of the
variables, so there likely is a pointer to q somewhere. But it's (IMHO)
irrelevant to this discussion, unless the extension is trying to look up
variables by name or something like that.

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20230113/3099aaae/attachment.sig>


More information about the Python-list mailing list