[Python-3000] empty set & dict syntax

David Goodger goodger at python.org
Fri Apr 28 16:01:38 CEST 2006


Sets and dicts are similar beasts, right?  "A set object is an
unordered collection of immutable values."  Dicts can be described as
sets with lookup values associated with the keys.  Sets can be
described as dicts with only keys, no values.

So how about creating a new base set/mapping type (call it 'baseset'
for now), use "{}" as the literal syntax of baseset instances, and
specialize dynamically on the first unambiguous use?  Empty sets
and empty dicts would *both* be spelled "{}".

For example:

>>> x = {}
>>> type(x)
<type 'baseset'>
>>> bool(x)        # common operation, doesn't alter type
False
>>> x['a'] = 1     # dict-only operation
>>> type(x)
<type 'dict'>
>>> y = {}
>>> y.add('a')     # set-only operation
>>> type(y)
<type 'set'>

Any specialized operation on an empty baseset instance determines its
type, even if the operation doesn't alter the instance:

>>> z = {}
>>> 'a' in z       # common operation, doesn't affect type
False
>>> type(z)
<type 'baseset'>
>>> z.items()      # dict-only operation
[]
>>> type(z)
<type 'dict'>

Initializing the baseset is an unambiguous operation:

>>> type({'a'})
<type 'set'>
>>> type({'a': 1}>
<type 'dict'>

--
David Goodger <http://python.net/~goodger>


More information about the Python-3000 mailing list