Achieve enumeration modoki without using enum

I wondered if the following variable definitions could be made smart, so I made a note. Please comment if you say "there is a better way".

STYLE_RED = 1
STYLE_BLUE = 2
STYLE_GREEN = 3
STYLE_YELLOW = 4
 :

I'm talking about "use enums", but since enums can't be used by default in Python 2.7 series, I'd like to make some tricks to realize it. (A backport of enum function called enum34 is also provided for Python 2.7 series)

point

These variable definitions are often added and deleted during development, and it is often necessary to shift all the values in the latter part, especially when adding a new definition between the defined variables.

STYLE_RED = 1
SYTLE_BLACK = 2  #I really want to add it here as 2
STYLE_BLUE = 3   #Shift the value in the latter stage
STYLE_GREEN = 4  #This is also..
STYLE_YELLOW = 5 #This is also...
 :

The point is whether or not such addition / deletion can be done quickly.

How to use tuples

Like this.

(
    RED,
    BLUE,
    GREEN,
    YELLOW,
) = range(0, 4)

print 'Color RED: %d' % RED

Since the values are not specified individually, it is not necessary to shift each time by adding a variable, but the second argument of the range () function must be changed at the same time.

(
    RED,
    BLACK,  #add to
    BLUE,
    GREEN,
    YELLOW,
) = range(0, 5)  # 4->Change to 5

By using tuples, it becomes an invariant variable, so it is very useful depending on the application. It looks like an enum, and you can process it sequentially by giving it a name.

COLORS = (
    RED,
    BLUE,
      :
) = range(0, ...)

Assign while incrementing the value using a variable

Since the ++ operation cannot be used in Python, the following implementation is not possible.

int colorVal = 0
int RED = colorVal++;
int BLUE = colorVal++;
  :

If you do this in Python, it will (probably) look like this:

_cv = 0
RED = _cv = (_cv + 1)
BLUE = _cv = (_cv + 1)
GREEN = _cv = (_cv + 1)
YELLOW = _cv = (_cv + 1)

Since the right side is the same expression, it is easy to add variables. However, the code doesn't look smart anyway, so I personally think that the tuple method is Python-like. (It's best to use enums obediently)

Recommended Posts

Achieve enumeration modoki without using enum
Modulo without using%
Bubble sort without using sort
Write FizzBuzz without using "="
Quicksort without using sort
Gamma correction without using OpenCV