10.2. Enum IntEnum
List of finite choices
Enumerations
IntEnum
Flag
IntFlag
10.2.1. IntEnum
>>> from enum import IntEnum
>>>
>>>
>>> class Color(IntEnum):
... RED = 1
... GREEN = 2
... BLUE = 3
>>>
>>>
>>> mycolor = Color.RED
>>>
>>> mycolor.name
'RED'
>>>
>>> mycolor.value
1
10.2.2. Auto
>>> from enum import IntEnum, auto
>>>
>>>
>>> class Color(IntEnum):
... RED = auto()
... GREEN = auto()
... BLUE = auto()
>>>
>>> for color in Color:
... print(color.name, color.value)
...
RED 1
GREEN 2
BLUE 3
10.2.3. Use Case - 1
>>> from enum import Enum, IntEnum
>>>
>>>
>>> class HTTPStatus(Enum):
... OK = 200
... CREATED = 201
... BAD_REQUEST = 400
... NOT_FOUND = 404
... INTERNAL_ERROR = 500
10.2.4. Use Case - 2
>>> from enum import Enum, IntEnum
>>>
>>>
>>> class Status(IntEnum):
... FULL_HEALTH = 100
... DEAD = 0
>>> hit_points = 100
>>> Status(hit_points)
<Status.FULL_HEALTH: 100>
>>> hit_points = 0
>>> Status(hit_points)
<Status.DEAD: 0>
10.2.5. Use Case - 3
>>> from enum import Enum, IntEnum
>>>
>>>
>>> class IndexDrives(IntEnum):
... ControlWord = 0x6040
... StatusWord = 0x6041
... OperationMode = 0x6060
10.2.6. Use Case - 4
Note, keycodes can vary depending on operating system and programming language used [mskeycodes], [jskeycodes].
>>> class Key(Enum):
... ESC = 0x01
... ARROW_LEFT = 0x61
... ARROW_UP = 0x57
... ARROW_RIGHT = 0x63
... ARROW_DOWN = 0x62
10.2.7. Use Case - 5
r
- readw
- writex
- executerwx
- read, write, execute; 0b111 == 0o7rw-
- read, write; 0b110 == 0o6r-x
- read, execute; 0b101 == 0o5r--
- read only; 0b100 == 0o4rwxr-xr--
- user=(read,write,execute); group=(read,execute); others=(read)
>>> from enum import Enum
>>> from pathlib import Path
>>>
>>>
>>> class Permission(Enum):
... READ_WRITE_EXECUTE = 0b111
... READ_WRITE = 0b110
... READ_EXECUTE = 0b101
... READ = 0b100
... WRITE_EXECUTE = 0b011
... WRITE = 0b010
... EXECUTE = 0b001
... NONE = 0b000
>>>
>>>
>>> file = Path('/tmp/myfile.txt')
>>> file.touch()
>>> file.stat()
os.stat_result(st_mode=33188, st_ino=98480473, st_dev=16777220,
st_nlink=1, st_uid=501, st_gid=20, st_size=0,
st_atime=1624458230, st_mtime=1624458230,
st_ctime=1624458230)
>>>
>>> permissions = file.stat().st_mode
>>> decimal = int(permissions)
>>> octal = oct(permissions)
>>> binary = bin(permissions)
>>> print(f'{decimal=}, {octal=}, {binary}')
decimal=33188, octal='0o100644', 0b1000000110100100
>>>
>>> *_, user, group, others = oct(permissions)
>>> print(f'{user=} {group=} {others=}')
user='6' group='4' others='4'
>>>
>>> Permission(int(user))
<Permission.READ_WRITE: 6>
>>>
>>> Permission(int(group))
<Permission.READ: 4>
>>>
>>> Permission(int(others))
<Permission.READ: 4>
>>>
>>> file.unlink()