`frozenset`, `frozendict` comprehensions. Consideration

1. Introduction

Potentially complete core container set:

  1. list & tuple
  2. set & frozenset
  3. dict & frozendict

Given the above, these are “missing”:

  1. set - no empty set literal
  2. frozenset - object exists, but nothing else
  3. frozendict - nothing exists, not even the object

To address (1), there are couple of threads:

  1. Initializer for set, like dict {} and list []
  2. Implement {,} as an empty set literal

To address (2), has been one attempt (as far as I know):

  1. Frozenset literals and comprehensions

To address (3), the first step of object creation:

  1. PEP 603: Adding a frozenmap type to collections
  2. I think there have been more attempts, but it is not relevant to this thread.

2. Consideration

(1) above is just for complete picture, but this is mostly about (2) and (3).

My thought process:

  1. So (2) was attempted and proved to be tricky (at least that specific solution).
  2. If frozendict was implemented, then instead of 1 full set of literals/comprehensions, 2 are lacking. And even one seems to be difficult.
  3. Thus, maybe what could work is something similar to “string type prefixes”?

Given set literal exists. E.g. {/}:

{/}    # Empty Set
f{/}   # Empty Frozen Set

{}     # Empty Dict
f{}    # Empty Frozen Dict

{a for a in iterable}           # set
f{a for a in iterable}          # frozenset

{a: b for a, b in iterable}     # dict
f{a: b for a, b in iterable}    # frozendict

Not necessarily f, but the idea is not to make up new brackets, but instead use the same syntax, but with some frozen indicator. Maybe prefix, maybe suffix, maybe something else entirely.

3. To sum up

If frozendict is indeed coming and comprehensions for both frozenset and frozendict are desirable, then solution that would capture comprehensions/literals for them both while drawing sensible/consistent parallels could be convenient/smooth path forward.

Thoughts?

4 Likes

I’m happy with the current form: frozenset({a for a in iterable}). That is clear and reasonably fast.

1 Like

And “{}” are redundant here, just frozenset(iterable) or frozenset(_.doit() for _ in iterable).

But I agree, there are clear workarounds without need for a new syntax, and this proposal lacks “Motivation“ section for lazy people like me, who (sometimes) don’t read previous discussions.

3 Likes

I like it!

1 Like

It seems what you mean with “literals” differs from the documentation (it’s just strings and some numbers, not even ()).

I am probably wrong with precise terminology.

I just mean “syntax for shorthand empty container and comprehensions”. However it is defined in strict terms.

1 Like

I’m gravitating towards the opposite point of view: That Python has too many comprehension variants already. That all we need is generator expressions passed to constructors.

3 Likes