[Python-ideas] IntFlags
Alexander Heger
python at 2sn.net
Wed Mar 4 19:49:25 CET 2015
>> One of the big questions that (IIRC) derailed this last time and got it
>> dropped from the enum stdlib design was: what does ~ do? Does it give you
>> the 2's complement negative integer? What does that display as in the str
>> and repr? And, if you add in conversion from an IntFlags to/from a set of
>> separate values, as has been suggested again in this thread, how does that
>> work? All of this is trivial when you're dealing with C fixed-size unsigned
>> ints: ~READ means 15 of the 16 bits (all except the READ bit) are set.
>
>
> IntFlags is just fancy int. int(~flags) == int(~int(flags)). Python supports
> ~ for arbitrary integers. ~x == -x-1
>
> There are no problems with conversions from a set to IntFlags, but the
> conversion from IntFlags to set is not always possible.
>
>> Another issue that came up was that C flags often have "combined" names
>> that are ambiguous: RDWR = RDONLY | WRONLY), which is fine until you want a
>> repr (in C, it's just going to print 3); does it have to be smart enough to
>> show RDWR? (Or, worse, RDWR | CLOEXEC.)
>
>
> This problem is nor so hard. My implementation was smart enough.
>
>>>> print(OpenMode.RDONLY | OpenMode.WRONLY | OpenMode.CLOEXEC)
> OpenMode.RDWR|OpenMode.CLOEXEC
>>>> print(~(OpenMode.RDONLY | OpenMode.WRONLY | OpenMode.CLOEXEC))
> ~(OpenMode.RDWR|OpenMode.CLOEXEC)
>
> Of course the repr can be senseless if the value is senseless (such as
> RDONLY | ~WRONLY).
Wouldn't it be possible to for the class to determine what bits are
all used from the constants defined, and then for the ~ operator to
just invert those? It may require some sanity check for users only
defining "combination constants" in the class such that the result
could not be represented.
class Stupid(IntFlags):
CAT = 3
DOG = 6
in which case ~CAT would not make sense, but neither could CAT | DOG
be represented. I suppose in such cases an error should be raised by
the metaclass on class definition.
-Alexander
More information about the Python-ideas
mailing list