[Python-ideas] a set of enum.Enum values rather than the construction of bit-sets as the "norm"?
Steven D'Aprano
steve at pearwood.info
Fri Dec 29 10:38:21 EST 2017
On Fri, Dec 29, 2017 at 10:26:22PM +1100, Chris Angelico wrote:
> On Fri, Dec 29, 2017 at 7:18 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> > Since ints don't provide a set-like interface, they aren't strictly
> > speaking bitsets. But in any case, nobody is stopping people from using
> > sets of enum values.
>
> I'm not sure what "set-like interface" you'd be looking for, but the
> built-in set type has a lot of the same operations as an integer does,
> and the semantics are virtually identical to a set of bits. The only
> one you really lack is __contains__, which could easily be added:
The lack of support for the `in` operator is a major difference, but
there's also `len` (equivalent to "count the one bits"), superset
and subset testing, various in-place mutator methods, etc. Java has a
BitSet class, and you can see the typical sorts of operations
commonly required:
https://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html
Of course we can emulate set-like operations using ints, but the
interfaces are different, which is my point. Here's how to clear all the
flags of a set or int:
the_flags.clear()
the_flags = 0 # clear all the bits in an int
Setting a flag is *almost* the same between the two:
the_flags |= {flag} # set
the_flags |= flag # int
although for sets, there are two other ways to set a flag which aren't
supported by ints:
the_flags.add(flag)
the_flags.update({flag})
Similarly for clearing flags:
the_flags.discard(flag)
the_flags & ~flag
--
Steve
More information about the Python-ideas
mailing list