0

I have some set of states.

my currently code:

STATE_0, STATE_1, STATE_3, STATE_4, STATE_5 = range(5)

Each time I need to add state, I have to do two things: change state and change range. This is error-prone. So I wrote this code to minimize it. Is this the best approach? Of course, I can create a dictionary or some other structure, but I think it will not be a "pythonic way" and not the shortest way.

STATE_0, STATE_1, STATE_3, STATE_4, STATE_5, *_ = range(1000)
martineau
  • 119,623
  • 25
  • 170
  • 301
salius
  • 113
  • 7
  • 1
    `states = {f'...{i}...': i for i in range(1000)}` isn't short enough? – chepner May 06 '20 at 17:23
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – r.ook May 06 '20 at 17:36

2 Answers2

3

Why not use the enum module like this:

from enum import IntEnum, auto
class State(IntEnum):
    ZERO = auto()
    ONE = auto()
    TWO = auto()

Using auto will automatically assign the next value so you can just keep adding states easily. And you can use it as with State.Zero.

L. MacKenzie
  • 493
  • 4
  • 14
  • Thank you, I am not familiar with this structure, I will learn more about it, but it requires import, which is not very good – salius May 06 '20 at 17:26
  • True, it does require an import, but enum is part of the standard library so not additional installation is required. – L. MacKenzie May 06 '20 at 17:32
0

I don't know what the rest of your code looks like, but my first reaction is to store STATEn as a list:

n = 1000
STATE = list(range(n))

and then to get indvidual states, you address them by index, e.g.

STATE[3]
bfris
  • 5,272
  • 1
  • 20
  • 37