[Python-ideas] IntFlags
Andrew Barnert
abarnert at yahoo.com
Wed Mar 4 16:17:49 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.
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.)
Sent from a random iPhone
On Mar 3, 2015, at 7:52, Serhiy Storchaka <storchaka at gmail.com> wrote:
> Enum and IntEnum classes allow constants to have nice str() and repr() representations.
>
> >>> socket.AF_INET
> <AddressFamily.AF_INET: 2>
> >>> socket.socket()
> <socket.socket fd=3, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('0.0.0.0', 0)>
>
> But when integer constants are flags that should be ORed, IntEnum doesn't help, because the result of bitwise OR of two IntEnum instances is int, and this value can't be represented as IntEnum.
>
> We need new type IntFlags. It is like IntEnum, but has differences:
>
> 1. The value of an instance should be not limited to the set of predefined constants. It can be a combination of predefined constants or even arbitrary integer.
>
> 2. The result of "|", "&" and "~" operators for IntFlags arguments should be an instance of the same IntFlags subclass.
>
> 3. It should have nice str() and repr().
>
> >>> print(stat.S_IROTH | stat.S_IWOTH)
> stat.S_IROTH|stat.S_IWOTH
> >>> stat.S_IROTH | stat.S_IWOTH
> <StatFlags.S_IROTH|S_IWOTH: 6>
>
> Any thoughts?
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
More information about the Python-ideas
mailing list