I just tried an augmented assignment on a frozenset, and the result surprised me:
>>> x = frozenset(['foo', 'bar', 'baz'])
>>> x
frozenset({'foo', 'baz', 'bar'})
>>> x &= {'baz', 'qux', 'quux'}
>>> x
frozenset({'baz'})
This isn't supposed to happen, is it? Aren't frozensets immutable?
Why are you surprised?
You knew the term "augmented assignment" so there is no problem finding the "Python Data Model on augmented arithmetic assignments" (emphasis mine):
So it has no
__iand__
method so the code you perform is:The
__and__
method however is defined byfrozenset
:However you lost your reference to the original
frozenset
:x
:But that just follows the "Principle of least astonishment". You wanted the
__and__
and you made it clear that you didn't want to keep your originalx
- an in-place operation also would have altered it!So again: Why did that surprise you?