[issue38250] enum.Flag should be more set-like
Ethan Furman
report at bugs.python.org
Wed Jan 13 23:20:53 EST 2021
Ethan Furman <ethan at stoneleaf.us> added the comment:
The code sample:
class Color(IntFlag):
BLACK = 0
RED = 1
GREEN = 2
BLUE = 4
PURPLE = RED | BLUE
WHITE = RED | GREEN | BLUE
Here's the summary of the changes:
- single-bit flags are canonical
- multi-bit and zero-bit flags are aliases
+ only canonical flags are returned during iteration
>>> list(Color.WHITE)
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>]
- negating a flag or flag set returns a new flag/flag set with the
corresponding positive integer value
>> Color.GREEN
<Color.GREEN: 2>
>> ~Color.GREEN
<Color.PURPLE: 5>
- `name`s of pseudo-flags are constructed from their members' names
>>> (Color.RED | Color.GREEN).name
'RED|GREEN'
- multi-bit flags, aka aliases, can be returned from operations
>>> Color.RED | Color.BLUE
<Color.PURPLE: 5>
>>> Color(7) # or Color(-1)
<Color.WHITE: 7>
- membership / containment checking has changed slightly -- zero valued flags
are never considered to be contained:
>>> Color.BLACK in Color.WHITE
False
otherwise, if all bits of one flag are in the other flag, True is returned:
>>> Color.PURPLE in Color.WHITE
True
There is a new boundary mechanism that controls how out-of-range / invalid bits are handled: `STRICT`, `CONFORM`, `EJECT', and `KEEP':
STRICT --> raises an exception when presented with invalid values
CONFORM --> discards any invalid bits
EJECT --> lose Flag status and become a normal int with the given value
KEEP --> keep the extra bits
- keeps Flag status and extra bits
- they don't show up in iteration
- they do show up in repr() and str()
The default for Flag is STRICT, the default for IntFlag is DISCARD, and the default for _convert_ is KEEP (see ssl.Options for an example of when KEEP is needed).
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38250>
_______________________________________
More information about the Python-bugs-list
mailing list