python-peps/peps/pep-0218.rst

215 lines
7.7 KiB
ReStructuredText
Raw Normal View History

PEP: 218
Title: Adding a Built-In Set Object Type
Author: Greg Wilson <gvwilson@ddj.com>, Raymond Hettinger <python@rcn.com>
Status: Final
2000-08-23 01:51:13 -04:00
Type: Standards Track
2017-01-24 15:47:22 -05:00
Content-Type: text/x-rst
Created: 31-Jul-2000
Python-Version: 2.2
2017-01-24 15:47:22 -05:00
Post-History:
Introduction
2017-01-24 15:47:22 -05:00
============
2017-01-24 15:47:22 -05:00
This PEP proposes adding a Set module to the standard Python
library, and to then make sets a built-in Python type if that
module is widely used. After explaining why sets are desirable,
and why the common idiom of using dictionaries in their place is
inadequate, we describe how we intend built-in sets to work, and
then how the preliminary Set module will behave. The last
section discusses the mutability (or otherwise) of sets and set
elements, and the solution which the Set module will implement.
Rationale
2017-01-24 15:47:22 -05:00
=========
Sets are a fundamental mathematical structure, and are very
commonly used in algorithm specifications. They are much less
frequently used in implementations, even when they are the "right"
structure. Programmers frequently use lists instead, even when
the ordering information in lists is irrelevant, and by-value
lookups are frequent. (Most medium-sized C programs contain a
depressing number of start-to-end searches through malloc'd
vectors to determine whether particular items are present or
not...)
Programmers are often told that they can implement sets as
dictionaries with "don't care" values. Items can be added to
these "sets" by assigning the "don't care" value to them;
membership can be tested using ``dict.has_key``; and items can be
deleted using ``del``. However, the other main operations on sets
2017-01-24 15:47:22 -05:00
(union, intersection, and difference) are not directly supported
by this representation, since their meaning is ambiguous for
dictionaries containing key/value pairs.
Proposal
2017-01-24 15:47:22 -05:00
========
2017-01-24 15:47:22 -05:00
The long-term goal of this PEP is to add a built-in set type to
Python. This type will be an unordered collection of unique
values, just as a dictionary is an unordered collection of
key/value pairs.
2017-01-24 15:47:22 -05:00
Iteration and comprehension will be implemented in the obvious
ways, so that::
2017-01-24 15:47:22 -05:00
for x in S:
2017-01-24 15:47:22 -05:00
will step through the elements of S in arbitrary order, while::
2017-01-24 15:47:22 -05:00
set(x**2 for x in S)
2017-01-24 15:47:22 -05:00
will produce a set containing the squares of all elements in S,
Membership will be tested using ``in`` and ``not in``, and basic set
2017-01-24 15:47:22 -05:00
operations will be implemented by a mixture of overloaded
operators:
============= =============================
``|`` union
``&`` intersection
``^`` symmetric difference
``-`` asymmetric difference
``== !=`` equality and inequality tests
``< <= >= >`` subset and superset tests
============= =============================
2017-01-24 15:47:22 -05:00
and methods:
================== =============================================
2017-01-24 15:47:22 -05:00
``S.add(x)`` Add "x" to the set.
2017-01-24 15:47:22 -05:00
``S.update(s)`` Add all elements of sequence "s" to the set.
2017-01-24 15:47:22 -05:00
``S.remove(x)`` Remove "x" from the set. If "x" is not
present, this method raises a ``LookupError``
exception.
2017-01-24 15:47:22 -05:00
``S.discard(x)`` Remove "x" from the set if it is present, or
do nothing if it is not.
2017-01-24 15:47:22 -05:00
``S.pop()`` Remove and return an arbitrary element,
raising a ``LookupError`` if the element is
not present.
2017-01-24 15:47:22 -05:00
``S.clear()`` Remove all elements from this set.
2017-01-24 15:47:22 -05:00
``S.copy()`` Make a new set.
2017-01-24 15:47:22 -05:00
``s.issuperset()`` Check for a superset relationship.
2017-01-24 15:47:22 -05:00
``s.issubset()`` Check for a subset relationship.
================== =============================================
2017-01-24 15:47:22 -05:00
and two new built-in conversion functions:
2017-01-24 15:47:22 -05:00
================ ===============================================
``set(x)`` Create a set containing the elements of the
collection "x".
2017-01-24 15:47:22 -05:00
``frozenset(x)`` Create an immutable set containing the elements
of the collection "x".
================ ===============================================
2017-01-24 15:47:22 -05:00
Notes:
1. We propose using the bitwise operators "``|&``" for intersection
and union. While "``+``" for union would be intuitive, "``*``" for
2017-01-24 15:47:22 -05:00
intersection is not (very few of the people asked guessed what
it did correctly).
2. We considered using "``+``" to add elements to a set, rather than
"add". However, Guido van Rossum pointed out that "``+``" is
symmetric for other built-in types (although "``*``" is not). Use
2017-01-24 15:47:22 -05:00
of "add" will also avoid confusion between that operation and
set union.
Set Notation
2017-01-24 15:47:22 -05:00
============
The PEP originally proposed ``{1,2,3}`` as the set notation and ``{-}`` for
the empty set. Experience with Python 2.3's ``sets.py`` showed that
2017-01-24 15:47:22 -05:00
the notation was not necessary. Also, there was some risk of making
dictionaries less instantly recognizable.
2017-01-24 15:47:22 -05:00
It was also contemplated that the braced notation would support set
comprehensions; however, Python 2.4 provided generator expressions
which fully met that need and did so it a more general way.
(See :pep:`289` for details on generator expressions).
2017-01-24 15:47:22 -05:00
So, Guido ruled that there would not be a set syntax; however, the
issue could be revisited for Python 3000 (see :pep:`3000`).
History
2017-01-24 15:47:22 -05:00
=======
To gain experience with sets, a pure python module was introduced
in Python 2.3. Based on that implementation, the set and frozenset
types were introduced in Python 2.4. The improvements are:
* Better hash algorithm for frozensets
* More compact pickle format (storing only an element list
instead of a dictionary of key:value pairs where the value
is always ``True``).
2017-01-24 15:47:22 -05:00
* Use a ``__reduce__`` function so that deep copying is automatic.
* The BaseSet concept was eliminated.
* The ``union_update()`` method became just ``update()``.
* Auto-conversion between mutable and immutable sets was dropped.
* The ``_repr`` method was dropped (the need is met by the new
``sorted()`` built-in function).
Tim Peters believes that the class's constructor should take a
single sequence as an argument, and populate the set with that
sequence's elements. His argument is that in most cases,
programmers will be creating sets from pre-existing sequences, so
that this case should be the common one. However, this would
require users to remember an extra set of parentheses when
initializing a set with known values::
>>> Set((1, 2, 3, 4)) # case 1
2017-01-24 15:47:22 -05:00
On the other hand, feedback from a small number of novice Python
users (all of whom were very experienced with other languages)
indicates that people will find a "parenthesis-free" syntax more
natural::
>>> Set(1, 2, 3, 4) # case 2
2017-01-24 15:47:22 -05:00
Ultimately, we adopted the first strategy in which the initializer
takes a single iterable argument.
2000-12-14 12:11:17 -05:00
Mutability
2017-01-24 15:47:22 -05:00
==========
The most difficult question to resolve in this proposal was
whether sets ought to be able to contain mutable elements. A
dictionary's keys must be immutable in order to support fast,
reliable lookup. While it would be easy to require set elements
to be immutable, this would preclude sets of sets (which are
widely used in graph algorithms and other applications).
Earlier drafts of :pep:`218` had only a single set type, but the
``sets.py`` implementation in Python 2.3 has two, Set and
2017-01-24 15:47:22 -05:00
ImmutableSet. For Python 2.4, the new built-in types were named
``set`` and ``frozenset`` which are slightly less cumbersome.
2017-01-24 15:47:22 -05:00
There are two classes implemented in the "sets" module. Instances
of the Set class can be modified by the addition or removal of
elements, and the ImmutableSet class is "frozen", with an
unchangeable collection of elements. Therefore, an ImmutableSet
may be used as a dictionary key or as a set element, but cannot be
updated. Both types of set require that their elements are
immutable, hashable objects. Parallel comments apply to the "set"
and "frozenset" built-in types.
Copyright
2017-01-24 15:47:22 -05:00
=========
This document has been placed in the Public Domain.