
On Sun, Jan 16, 2022 at 06:10:58PM -0800, Christopher Barker wrote:
In a way, what this might do is open the door to interning (some) frozen sets, like cPython does for some ints and strings.
I don't think that interning is relevant here. Interning is orthogonal to the existence of a frozenset display. You don't need to use a literal or display syntax to take advantage of interning: # At least some versions of CPython >>> m = int('78') >>> n = int('78') >>> m is n True And the existence of a literal or display syntax does not imply interning, e.g. floats, tuples. If there was a use for interning frozensets, we could do so regardless of whether or not there is a display syntax.
(using f{...} as a frozenset literal) does something different - it returns the *same* object, compiled once at function definition time, every time it's called.
why/how would it do that? It *could* do that -- as above, with interning.
Inside a function, CPython can cache literals and immutable displays made from purely literals, e.g. the tuple (1, 2, 3) but not the tuple (1, 2, x)) in co_consts. But we can't do any of that if the only way to create a frozenset is to lookup the name "frozenset" and call that function. So while not all frozensets inside a function could be built at compile-time and retrieved from co_consts, some of them could -- if only we had a display syntax equivalent to tuple displays. Ironically, if the compiler can prove that a regular mutable set display is only ever used once inside a function, CPython will make it a frozenset:
def func(a): ... return a in {1, 2, 4} ... func.__code__.co_consts (None, frozenset({1, 2, 4}))
So ironically the only way to put a constant frozenset into co_consts is to write it as a mutable set and only use it once!
We don't make changes to Python syntax unless there is a compelling reason.
"Compelling" depends on the cost of making the change. The bigger the cost, the more compelling the reason. The smaller the change, then the reason need not be as huge. I think this is a small change with a moderate benefit, which puts the cost vs benefit ratio on the benefit side.
There are any number of python types with no "literal" (well, not any number, it's quite defined. but still) heck, we don't even have literals for Decimal. Why this one?
Nearly all of those types are not builtins. As far as I can see, frozenset is the only commonly used, immutable, builtin type that doesn't have a literal display syntax, and the consequence of that is that code using frozensets does much more work than needed. -- Steve