4

Is that a good way to define a class like this:

class states:
    INACTIVE = 'Inactive'
    ACTIVE = 'Active'
    PENDING = 'Pending'
    BANNED = 'Banned'

to keep a list of possible values and then get them as, e.g. states.INACTIVE, so when I want to change user's status, I do something like this: user.status=states.BANNED and it gets value 'Banned'. I use it to quickly access these values with IntelliSense in my IDE with ctrl-space and it also makes it safer against typos. Though, I am not sure it's a good approach to create a class for just keeping some strings. How can I organize it a better way or is that a good solution?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

4 Answers4

4

I think this solution is OK. But maybe I would add those constants to the user class:

class User:
    STATUS_INACTIVE = 'Inactive'
    STATUS_ACTIVE = 'Active'
    STATUS_PENDING = 'Pending'
    STATUS_BANNED = 'Banned'

    def __init__(self):
        self.status = User.STATUS_ACTIVE
Elalfer
  • 5,312
  • 20
  • 25
1

It seems like what you want is an enumeration.

Community
  • 1
  • 1
nmichaels
  • 49,466
  • 12
  • 107
  • 135
1

You could also provide these as module-level variables in a distinct states module:

# states.py
INACTIVE = 'Inactive'
ACTIVE = 'Active'
PENDING = 'Pending'
BANNED = 'Banned'

And then import states in your code:

# example.py
import states

# ... stuff happens to create user instance
user.status = states.BANNED

With this method there is no need to instantiate a class just to pull variables from it. I have no idea whether or not this is the most efficient route, but it is very convenient.

jathanism
  • 33,067
  • 9
  • 68
  • 86
1

I am using this at number of places. And think it is perfectly ok.

Shekhar
  • 7,095
  • 4
  • 40
  • 45