[Python-ideas] IntFlags

Chris Kaynor ckaynor at zindagigames.com
Thu Mar 5 23:34:54 CET 2015


On Thu, Mar 5, 2015 at 2:07 PM, Eugene Toder <eltoder at gmail.com> wrote:
> On Thu, Mar 5, 2015 at 3:30 PM, Greg Ewing <greg.ewing at canterbury.ac.nz>
> wrote:
>>
>> Concerning ~, if you think of it as a set, then ~x should
>> be the result of exlusive-oring x with an int containing
>> all the valid bits, i.e. the value obtained by oring all
>> the defined values together.
>
> Yes, that will work. Then we might want predefined constants for all set
> bits and zero. (Zero can be just calling MyBitSet() with no arguments). Then
> ~X is type(X).ALL_ONES - X.
> The main question is whether this operation makes much sense. I think in
> practice ~ is only used with flags to clear bits (X & ~Y), which can be done
> in one explicit operation. It may still be worth supporting ~ to allow
> painless transition from plain ints.

I wonder if it would be worth it to have an ALL value supported, which
defaults to the other values ored together, but could be overridden
for specific cases. This could be useful for compatibility with C code
where there are not publicly defined values for some bits, but they
have some meaning (possibly only for compatibility). If it were purely
computed automatically, handling of cases where there are unused bits
could get messy in some cases. Even if methods are implemented for
clearing flags (the primary case for bit-wise not on a bit field),
supporting a bit-wise not would still be extremely useful for
compatibility with other languages.

In terms of printing, I would expect that, for ease of reading, a
negated flags would print with the negation (storing it as
one-complement), however every other operation would collapse the
negation into the full int value, losing the printing value. Something
like:

>>> READ = 1; WRITE = 2; EXECUTE = 4 # Obviously, different syntax. This would default ALL = 4 | 2 | 1, however it could be overridden in the special cases where other values have meaning. I would imagine the most common override would be to 0xFFFFFFFF, though I could also see others.
>>> a = READ | EXECUTE
>>> a
(READ | EXECUTE)
>>> ~a # Stores it as a negation of the values.
~(READ | EXECUTE)
>>> b = EXECUTE | WRITE
>>> b # Reordered based on values.
(WRITE | EXECUTE)
>>> b & ~a # Collapses the negation into the full bit field, resulting in a non-negated bit field.
WRITE
>>> ~b | ~a
(READ | WRITE)

On Thu, Mar 5, 2015 at 1:22 PM, Chris Angelico <rosuav at gmail.com> wrote:
> As the other Chris says, it's basically the bit with name "n",
> and then we give it a much more convenient alias.

Now that I've joined the conversation, there are TWO other Chris's :).


More information about the Python-ideas mailing list