[Python-Dev] List mutation in list_repr?

2016-12-06 Thread Patrick Westerhoff
Hey all,

I just stumbled on the following comment in the C source of the repr
implementation for the list object:

/* Do repr() on each element. Note that this may mutate the list,
   so must refetch the list size on each iteration. */

(as seen in list_repr implementation [1])

I’m honestly very surprised about this remark since I can neither
understand why this would be the case (repr shouldn’t mutate the
list), and I also don’t see any clue in the source as to when this
would actually happen. Since inside the loop, the list object `v` is
never accessed other than passing `v->ob_item[i]` to the recursive
repr call, there shouldn’t be any mutation on the list object itself.

I understand that a custom repr implementation could theoretically
mutate an object, but this could only affect the object itself (or its
children), but not the container list. So the list object `v` here
should be safe from mutations.

I tried looking at the original change when this was introduced.
Unfortunately, this was in 2001 [2], so I don’t really expect Tim to
still know *why* the comment was added back then.

Do you have any insights on why the comment is there, and whether I am
missing something that could actually mutate the list, making the size
refetch necessary and the comment justified?

Thanks a lot!
Patrick


[1] 
https://github.com/python/cpython/blob/b8519e4d08a82da9aa438d531058100c0e3d04b4/Objects/listobject.c#L361
[2] 
https://github.com/python/cpython/commit/bce15a39b30b0f5866e7b48ba3c29c3aa430a766
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] List mutation in list_repr?

2016-12-07 Thread Patrick Westerhoff
On Tue, Dec 6, 2016 at 5:32 PM, Random832  wrote:
> It *shouldn't*, but it can't be enforced. It's one of those things where
> if Python assumes all user code is sane (in this case, overridden
> __repr__ not messing with the list) it can bite in a way that could
> cause the interpreter to crash.

I guess you are right. That makes sense. I didn’t think about the
possibility that although the repr implementation is happening in
native code where the user objects have no access to, the list object
could still be referenced outside of the repr call.

Thanks a lot for the explanation and your example!

And also thank you Hrvoje Niksic!
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com