[Python-ideas] IntFlags

Serhiy Storchaka storchaka at gmail.com
Thu Mar 5 18:11:48 CET 2015


On 05.03.15 01:42, Andrew Barnert wrote:
> I think you're also right that using signed 1's complement is the best way to handle negated flags, despite the tradeoffs (not being able to compare to negated C values, having a confusing numerical value in the repr, having silly str for silly cases), especially since that's what ~ already does with IntEnum (except that the result is just plain int, of course).

Sorry, I don't understand your argument. Why you can't compare 
complemented IntFlags with complemented int?

~(os.OpenMode.O_CLOEXEC) == int(~os.OpenMode.O_CLOEXEC) == 
~int(os.OpenMode.O_CLOEXEC) == posix.O_CLOEXEC

IntFlags is an int subclass and behaves as plain int, except that it has 
special repr and results of bitwise operations preserve a type.

> * The parenthetical brings up another issue: if you look in your platform's sys/stat.h (or whichever header actually defines these things), S_IRWXG is probably not defined as 0o700, but as S_IRGRP | S_IWGRP | S_IXGRP. Can we do that in the enum definition? If not, it may be less readable than the C. (In fact, on many platforms, S_IRGRP is itself defined as something like _S_IREAD << _S_GRP, and S_IRWXG may be defined as (_S_IREAD | _S_IWRITE | _S_IEXEC) << _S_GRP. I think Linux took this even further and defined it as S_IRWXU >> (_S_USR - _S_GRP) or something silly. But at that point, not being able to clone the C no longer looks like a loss of readability...)

Yes, of course you can define:

class Permissions(enum.IntFlags):
     S_IRGRP = 0o0040  # read by group
     S_IWGRP = 0o0020  # write by group
     S_IXGRP = 0o0010  # execute by group
     S_IRWXG = S_IRGRP | S_IWGRP | S_IXGRP
     ...

or what your like. I tried and this works.



More information about the Python-ideas mailing list