frozenset can be altered by |=

David Raymond David.Raymond at tomtom.com
Mon Nov 22 08:51:13 EST 2021


>> (venv_3_10) marco at buzz:~$ python
>> Python 3.10.0 (heads/3.10-dirty:f6e8b80d20, Nov 18 2021, 19:16:18)
>> [GCC 10.1.1 20200718] on linux
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> a = frozenset((3, 4))
>> >>> a
>> frozenset({3, 4})
>> >>> a |= {5,}
>> >>> a
>> frozenset({3, 4, 5})
> 
> That's the same as how "x = 4; x += 1" can "alter" four into five.
> 
> >>> a = frozenset((3, 4))
> >>> id(a), a
> (140545764976096, frozenset({3, 4}))
> >>> a |= {5,}
> >>> id(a), a
> (140545763014944, frozenset({3, 4, 5}))
> 
> It's a different frozenset.
> 
> ChrisA

Another possible option is instead of

a |= {5,}

change it to

a.update({5,})

If a is a regular set it will update the original object, and if a is a frozenset it will raise an AttributeError. Which may not be what you want, but at least it won't quietly do something you weren't expecting.

It is a little confusing since the docs list this in a section that says they don't apply to frozensets, and lists the two versions next to each other as the same thing.

https://docs.python.org/3.9/library/stdtypes.html#set-types-set-frozenset

The following table lists operations available for set that do not apply to immutable instances of frozenset:

update(*others)
set |= other | ...

    Update the set, adding elements from all others.


More information about the Python-list mailing list