[Python-3000] Set literal

Raymond Hettinger python at rcn.com
Thu Jan 24 23:32:02 CET 2008


I think it would be more useful for the {e1, e2, e3} literal to be a frozenset instead of a set.

In expressions like "x in {'html', 'xml', 'php'}" the compiler could optimize away the set construction and treat it as a constant.

In cases where we want to build-up mutable sets, we need to start with set() anyway:

    s = set()
    for elem in source:
        s.add(elem)

I don't think it would be typical to start with a partially filled-out set and then build-t up further:

   s = {'a', 'b', 'c'}   # rare use-case
   for elem in source:
       s.add(elem)

One of the primary use cases for frozensets is to be members of other sets or to be keys in a dict (esp. for graph representations).  The repr's of those nested structures are annoying to read because the word "frozenset" gets spelled-out over and over again.  Here's a few lines from the pprint() output for a graph of a cube:

  {frozenset([0, 1]): frozenset([frozenset([0]),
                                 frozenset([1]),
                                 frozenset([0, 1, 2])]),
   frozenset([0, 1, 2]): frozenset([frozenset([1, 2]),
                                    frozenset([0, 2]),
                                    frozenset([0, 1])])}


This would read *much* better with the new notation:

  {{0, 1}: {{0},
            {1},
            {0, 1, 2}},
  {0, 1, 2}: {{1, 2},
              {0, 2},
              {0, 1}}}

If you want to see how extremely bad the current repr's can get, see the repr for David Eppstein's cuboctahedron in the tests for pprint:  http://mail.python.org/pipermail/python-checkins/2008-January/065099.html

In short, I think we would be much better served by using the {} literal notation for frozensets.

Raymond


P.S.  A small side-benefit is it may put an end for interminable requests for a {:} or {/} notation for empty sets.  There's not much need for a literal for a empty frozenset (use "not s" instead).



More information about the Python-3000 mailing list