[Python-ideas] IntFlags

Ethan Furman ethan at stoneleaf.us
Sat Mar 7 16:05:05 CET 2015


On 03/07/2015 05:53 AM, Andrew Barnert wrote:
> On Mar 7, 2015, at 12:07 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
>>
>>> On 03/03/2015 07:52 AM, Serhiy Storchaka wrote:
>>>
>>> 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().
>>
>> As long as we are dreaming  :)
>>
>> class Stat(IntFlag):
>>    RDONLY = 1
>>    NOSUID = 2
>>    NODEV = 4
>>    NOEXEC = 8
>>    SYNCHRONOUS = 16
>>    MANDLOCK = 64
>>    WRITE = 128
>>    APPEND = 256
>>    NOATIME = 1024
>>    NODIRATIME = 2048
>>    RELATIME = 4096
>>
>> a = Stat.RDONLY  # creates a new instance of Stat, not a singleton
> 
> Why?

Because by having mutable instances of Stat we can have more Python operations:

instead of:

  x = Stat(some_Stat_value_from_somewhere)
  x = x | Stat.NOEXEC  # to set the bit

we can say:

  x = Stat(some_Stat_value_from_somewhere)
  x.NOEXEC = True

or, even more illustratively, instead of:

  x = Stat(some_Stat_value_from_somewhere)
  x &= ~Stat.NOEXEC  # to clear the bit

we can have:

  x = Stat(some_Stat_value_from_somewhere)
  x.NOEXEC = False  # much more readable


> Assuming the values are immutable (like int), [...]

Drat.  Instances of Stat would not be immutuable, but that means they can't be thin wrappers around `int`, doesn't it?
Which also means more work around C call sites.  Drat and double-drat.


>> repr(~d)  # <Stat.RELATIME|NODIRATIME|NOATIME|512|APPEND|WRITE|SYNCHONOUS|NOEXEC|NODEV|NOSUID: 8094>
>>
>> I'm not at all sure I have that last one correct.
> 
> That last one is the big question. In C, ~d is going to have the 8192, 16384, ... 2b
> bits set, not just the bits you defined and the gaps in between. Are you sure you want
> a different result in Python? (Especially if you're on a platform that does something
> with those extra bits, so you can get values back that actually have them set.
> Although I don't think that's an issue with stat, it is with lots of other flags from
> POSIX-land.)

A `bytes` (or `byte_size`) would need to be set to control how many bits got flipped.  If not set, then only defined
bits get flipped.

--
~Ethan~

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150307/b5a8c36f/attachment.sig>


More information about the Python-ideas mailing list