On Sun, Jan 16, 2022 at 04:43:36PM -0800, Christopher Barker wrote:

> I’m a bit confused — would adding a “literal” form for frozenset  provide
> much, if any, of an optimization?

Yes. In at least some cases, it would avoid going through the song and 
dance:

1. create a frozenset
2. convert the frozenset to a regular set
3. convert the regular set back to a frozenset
4. garbage collect the regular set

See the b.p.o. ticket referenced earlier, as well as the disassembled 
code.

In other cases it would avoid:

1. create a set, tuple or list
2. create a frozenset
3. garbage collect the set, tuple or list

It would also avoid the name lookup of `frozenset`, and guarantee that 
even if that name was shadowed or monkey-patched, you still get a 
genuine frozenset.

(Just as [1, 2, 3] is guaranteed to return a genuine list, even if the 
name "list" is deleted, shadowed or replaced.)

At the moment, sets and frozensets still share the same implementation, 
but some years ago Serhiy suggested that he had some optimizations in 
mind that would make frozensets smaller than regular sets.


> How often do folks need a frozen set literal? I don’t think I’ve ever used
> one.

If you are writing `if x in ("this", "that", "another", "more")` then 
you probably should be using a frozenset literal, since membership 
testing in sets is faster than linear search of a tuple.

I think that the CPython peephole optimizer actually replaces that 
tuple with a frozenset, which is cool, but you can defeat that 
optimization and go back to slow linear search by refactoring the code 
and giving the targets a name:

    targets = ("this", "that", "another", "more")
    if x in targets: ...


> If we did, then f{‘this’: ‘that’} should make a frozen dict, yes?

We would have to get a frozen dict first, but if we did, that would be 
an obvious syntax to use.


-- 
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EEJQ5ZL76RZN2DONSELJQFKVV7MG4NEX/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to