Skip to content

Instantly share code, notes, and snippets.

@mkpoli
Last active January 16, 2021 04:40
Show Gist options
  • Select an option

  • Save mkpoli/861038f440a924506bee5ad22b1df1a2 to your computer and use it in GitHub Desktop.

Select an option

Save mkpoli/861038f440a924506bee5ad22b1df1a2 to your computer and use it in GitHub Desktop.
Dynamically extend Enum with property-methods in Python
from enum import Enum
Shape = Enum('Shape', ['I', 'O', 'J', 'L', 'T', 'Z', 'S'])
SHAPE_COORDS = {
Shape.I: [(0, 0), (0, 1), (0, 2), (0, 3)], # |
Shape.O: [(0, 0), (1, 0), (0, 1), (1, 1)], # [+]
Shape.J: [(0, 3), (1, 1), (1, 2), (1, 3)], # _|
Shape.L: [(0, 0), (0, 1), (0, 2), (1, 2)], # |_
Shape.T: [(0, 0), (1, 0), (0, 1), (1, 1)], # _|_
Shape.Z: [(0, 0), (1, 0), (0, 1), (1, 1)], # ^|_
Shape.S: [(0, 0), (1, 0), (0, 1), (1, 1)], # _|^
}
SHAPE_COLORS = {
Shape.I: "lightblue", # |
Shape.O: "yellow", # [+]
Shape.J: "blue", # _|
Shape.L: "orange", # |_
Shape.T: "purple", # _|_
Shape.Z: "red", # ^|_
Shape.S: "green", # _|^
}
def add_method(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
def add_property(cls):
def decorator(func):
setattr(cls, func.__name__, property(func))
return func
return decorator
@add_property(Shape)
def coord(self):
return SHAPE_COORDS[self]
@add_method(Shape)
def get_color(self):
return SHAPE_COLORS[self]
def main():
for shape in Shape:
print(shape.name, shape.coord, shape.get_color())
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment