🐍 Python - Enums
Updated at 2018-06-11 03:01
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)
# Color.RED
assert repr(Color.RED) == '<Color.RED: 1>'
assert type(Color.RED) == Color
assert isinstance(Color.GREEN, Color)
assert Color(1) == Color.RED
assert Color['RED'] == Color.RED
member = Color.RED
assert member.name == 'RED'
assert member.value == 1
for color in Color:
print(color)
There are also enum int flags.
from enum import IntFlag
class Permission(IntFlag):
R = 4
W = 2
X = 1
assert Permission.R | Permission.W == 6
assert Permission.R + Permission.W == 6
RW = Permission.R | Permission.W
assert Permission.R in RW
assert Permission.W in RW
assert Permission.X not in RW
assert Permission.R & Permission.X == 0
assert not bool(Permission.R & Permission.X)
Enum usage in Django models:
from django.db import models
from enumfields import EnumField
from enums import Color
class Shirt(models.Model):
color = EnumField(Color)