[Python-Dev] List mutation in list_repr? (original) (raw)

Random832 random832 at fastmail.com
Tue Dec 6 11:32:27 EST 2016


On Tue, Dec 6, 2016, at 05:27, Patrick Westerhoff wrote:

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 listrepr 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)

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.

class EvilClass: ... def repr(x): ... l.pop() ... return 'x' ... l = [EvilClass()]*10 l [x, x, x, x, x]

, 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->obitem[i] to the recursive repr call, there shouldn’t be any mutation on the list object itself.

The item may have or be able to a reference to the list object otherwise, as I demonstrated.



More information about the Python-Dev mailing list