Lux-AI-Challenge / Lux-Design-S1

Home to the design and engine of the @Lux-AI-Challenge Season 1, hosted on @kaggle
https://lux-ai.org/
Apache License 2.0
897 stars 151 forks source link

Use Python Enum for constants #99

Open Gerenuk opened 3 years ago

Gerenuk commented 3 years ago

A suggestion would be to use Python Enum for constants, because they provide some small advantages over plain class constants. For example

from enum import Enum

class DIRECTION(Enum):
    NORTH = "n"
    WEST = "w"
    SOUTH = "s"
    EAST = "e"
    CENTER = "c"

While they can be used similarly as in the previous version, small advantages - apart from being more pythonic - are

>>> list(DIRECTION)                    # possible to iterate; very useful sometimes
[<DIRECTION.NORTH: 'n'>,
 <DIRECTION.WEST: 'w'>,
 <DIRECTION.SOUTH: 's'>,
 <DIRECTION.EAST: 'e'>,
 <DIRECTION.CENTER: 'c'>]

>>> DIRECTION.NORTH.name    # access to readable name for print output
'NORTH'

>>>  DIRECTION.NORTH.value   # access to raw string value, but there shouldn't be a reason, unless you process external output
'n'

Other advantages are that type-checkers like mypy will notice if you accidentally compare them against unrelated strings. However, note that if for whatever reason you introduce raw strings instead of using the proper class, you will need to access the value with DIRECTION.NORTH.value (for example for if my_direction.value == "n":)