PEP 841 proposes syntax for frozen sets and dictionaries that could let Python optimize constant displays. Is the syntax worth adding, and is the f prefix clear enough?
What do you think of Python's proposed frozen display syntax?
Answers
The compiler guarantee is the interesting bit to me, more than saving a few characters. A call like frozenset({...}) has to look up a name that could have been rebound. A frozen display tells the compiler what type to produce from the syntax itself.
The proposal says a fully constant display can be folded into a single LOAD_CONST and cached in a .pyc file. That doesn't mean every frozen display is a constant, though. A frozen dictionary can still contain a mutable value, so the immutability is shallow.
Reply to this answer
I like having a concise way to write these, but f{1, 2, 3} makes me think of an f-string at a glance. The prefix would mean formatting in one place and freezing in another.
Something like frozen{1, 2, 3} or fz{1, 2, 3} would be easier for me to read, even if it's a little longer.
Velnor.3q:
The prefix is also easy to miss when scanning a display. Removing or adding it changes the resulting type, unlike an f-string prefix with no formatting expressions.
Reply to this answer
I'm not convinced this needs dedicated syntax. Making immutable containers easier to use sounds useful, but every new form adds something readers have to learn. I'd want the optimization benefit to justify that cost.
Reply to this answer
A broader const feature is more appealing to me than a prefix just for frozen displays. That would be a different proposal, though. Guaranteeing immutability for arbitrary complex objects is a much harder problem than producing a frozen container.
Reply to this answer
Add your answer
Answers are reviewed before publication.
q.729+ticketspoke:
That distinction seems worth making prominent. Freezing the dictionary doesn't freeze a list stored inside it.