Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using classes to keep predefined strings

Tags:

python

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?

like image 593
Sergei Basharov Avatar asked Oct 16 '25 14:10

Sergei Basharov


2 Answers

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
like image 99
Elalfer Avatar answered Oct 18 '25 06:10

Elalfer


It seems like what you want is an enumeration.

like image 42
nmichaels Avatar answered Oct 18 '25 06:10

nmichaels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!