10.5. Enum Flag
Flag
Flag
IntFlag
Flags have an expanded view of aliasing: to be canonical, the value of a flag needs to be a power-of-two value, and not a duplicate name. So, in addition to the Enum definition of alias, a flag with no value (a.k.a. 0) or with more than one power-of-two value (e.g. 3) is considered an alias.
SetUp:
>>> from enum import Flag
Definition:
>>> class Permission(Flag):
... READ = 0b100
... WRITE = 0b010
... EXECUTE = 0b001
Usage:
>>> Permission(1)
<Permission.EXECUTE: 1>
>>>
>>> Permission(2)
<Permission.WRITE: 2>
>>>
>>> Permission(3)
<Permission.WRITE|EXECUTE: 3>
>>>
>>> Permission(4)
<Permission.READ: 4>
>>>
>>> Permission(5)
<Permission.READ|EXECUTE: 5>
>>>
>>> Permission(6)
<Permission.READ|WRITE: 6>
>>>
>>> Permission(7)
<Permission.READ|WRITE|EXECUTE: 7>
Example:
>>> permission = Permission.READ | Permission.WRITE
>>> permission
<Permission.READ|WRITE: 6>
10.5.1. SetUp
>>> from enum import Flag
10.5.2. Recap
-rw-r--r-- 1 matt 5.0K 2024-06-27 20:06 README.rst
user = rw- = 0b110 = 6
group = r-- = 0b100 = 4
others = r-- = 0b100 = 4
10.5.3. Example
>>> class Permission(Flag):
... READ = 4
... WRITE = 2
... EXECUTE = 1
>>>
>>>
>>> myfile = Permission(5)
>>>
>>> myfile
<Permission.READ|EXECUTE: 5>
10.5.4. Flag
>>> class Permission(Flag):
... READ = 0b100
... WRITE = 0b010
... EXECUTE = 0b001
>>>
>>>
>>> myfile = Permission(5)
>>>
>>> myfile
<Permission.READ|EXECUTE: 5>