frozenset can be altered by |=

Chris Angelico rosuav at gmail.com
Mon Nov 29 17:01:22 EST 2021


On Tue, Nov 30, 2021 at 8:55 AM Marco Sulla
<Marco.Sulla.Python at gmail.com> wrote:
>
> I must say that I'm reading the documentation now, and it's a bit
> confusing. In the docs, inplace operators as |= should not work. They
> are listed under the set-only functions and operators. But, as we saw,
> this is not completely true: they work but they don't mutate the
> original object. The same for += and *= that are listed under `list`
> only.
>

Previously explained here:

> > On Mon, 22 Nov 2021 at 14:59, Chris Angelico <rosuav at gmail.com> wrote:
> > >
> > > Yeah, it's a little confusing, but at the language level, something
> > > that doesn't support |= will implicitly support it using the expanded
> > > version:
> > >
> > > a |= b
> > > a = a | b
> > >
> > > and in the section above, you can see that frozensets DO support the
> > > Or operator.
> > >
> > > By not having specific behaviour on the |= operator, frozensets
> > > implicitly fall back on this default.
> > >

The docs explicitly show that inplace operators are defined for the
mutable set, and not defined for the immutable frozenset. Therefore,
using an inplace operator on a frozenset uses the standard language
behavior of using the binary operator, then reassigning back to the
left operand.

This is a language feature and applies to everything. You've seen it
plenty of times with integers, and probably strings too. A frozenset
behaves the same way that anything else does.

ChrisA


More information about the Python-list mailing list