A question on modification of a list via a function invocation

Steve D'Aprano steve+python at pearwood.info
Fri Sep 8 09:33:33 EDT 2017


On Fri, 8 Sep 2017 05:54 pm, Gregory Ewing wrote:

> Steve D'Aprano wrote:
>> py> class K: # defines an object
>> ...     def __init__(self, x):
>> ...             self.x = x
>> ...     def append(self, value):
>> ...             self.x.append(value)
>> ...
>> py> a = []
>> py> b = K(a)
>> py> a is b  # these are not the same object (they're different types)
>> False
>> py> b.append(99)  # but modifying b modifies a
>> py> a
>> [99]
> 
> You didn't mutate the object bound to b there,
> you mutated the one bound to b.x, which is
> also bound to a.

Of course I do -- I've mutated one of the parts of the whole, therefore the
whole is mutated too.

Would you argue that if I took a hammer to your computer's motherboard, smashing
it to bits, that I haven't damaged your computer?

My class K is just a minimal sketch of a class that uses dependency injection
and composition, but that's not critical. Any compound object which has
publicly visible mutable parts is subject to the same sort of false positive:

book = Book()
assert book.annotations == []
page = book.pages[15]
assert book is not page  # the whole is not the same as the part
page.annotate(
    'Is this the right room for an argument?')  # but if you mutate the part
assert book.annotations == [15]  # the whole mutates too




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list