Class Variable Access and Assignment

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Nov 6 05:33:33 EST 2005


On Sun, 06 Nov 2005 08:40:00 +0000, Bengt Richter wrote:

>>Pre-conditions: class.a exists and is mutable; instance.a does
>>not exist.
>>Post-conditions: class.a modified; instance.a does not exist.
>>
> Are you saying the above is what happens or what should happen or not happen?

Er, it's what I thought was happening without actually checking it...

> It's not what happens. Post-conditions are that class.a is modified AND
> instance.a gets a _separate_ reference to the same result. Note:

[snip demonstration]
 
> Is that the "wart" you were thinking of, or are you actually happier?
> ;-)

In other words, the post-condition for all four scenarios includes that
the instance attribute now exists. I'm actually happier. My brain was full
of people talking about __iadd__ modifying mutables in place and I wasn't
thinking straight.


>>Well, that is a wart. It is the same wart, and for the same reasons, as
>>the behaviour of:
>>
>>def function(value=[]):
>>    value.append(None)
> IMO that's not a wart at all, that's a direct design decision, and it's
> different from the dual referencing that happens in Scenario 4.

Okay, perhaps wart is not quite the right word... but it is certainly
unexpected if you haven't come across it before, or thought *deeply* about
what is going on. A gotcha perhaps.


-- 
Steven.




More information about the Python-list mailing list