[Python-ideas] IntFlags

Serhiy Storchaka storchaka at gmail.com
Wed Mar 4 16:54:29 CET 2015


On 04.03.15 17:17, Andrew Barnert wrote:
> 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).




More information about the Python-ideas mailing list