Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Python Enum for constants #99

Open
Gerenuk opened this issue Jul 23, 2021 · 0 comments
Open

Use Python Enum for constants #99

Gerenuk opened this issue Jul 23, 2021 · 0 comments
Assignees
Labels
enhancement New feature or request starter-kit anything related to kit updates

Comments

@Gerenuk
Copy link

Gerenuk commented Jul 23, 2021

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":)

@StoneT2000 StoneT2000 added enhancement New feature or request starter-kit anything related to kit updates labels Jul 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request starter-kit anything related to kit updates
Projects
None yet
Development

No branches or pull requests

3 participants