0

Is it pythonic to define related consts like this?

define:

class LinkChoices(object):
    FOLLOW, FRIENDSHIP, CLOSE_FRIENDSHIP, = 10, 20, 30,

using:

from  some_module import LinkChoices

link.status = LinkChoices.FOLLOW

Are there any cons of defining consts like this?

kharandziuk
  • 12,020
  • 17
  • 63
  • 121
  • There is a lot of debate over what is pythonic and what isn't, this is fine so don't worry about it – jamylak Mar 24 '13 at 11:29

2 Answers2

1

Yes, I think it's pretty Pythonic, except that I wouldn't use ALL_CAPS for the class name.

I also don't see the point in the trailing commas.

Finally, I personally would probably define one constant per line rather than lumping them together on the same line.

For further discussion, see How to create a constant in Python

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

As suggested in the linked thread, you can also be defensive and take measures against accidental redefinition of your constants, for example:

def const(cls):
    class _const(type):
        def __setattr__(self,name,value):
            raise ValueError("Can't rebind const(%s)" % name)
    class _(cls):
        __metaclass__ = _const
    return _

@const
class LinkChoices(object):
    FOLLOW, FRIENDSHIP, CLOSE_FRIENDSHIP, = 10, 20, 30,

LinkChoices.FOLLOW = 123 # raises ValueError

Don't know if this is "pythonic" though. I'd say rather not.

georg
  • 211,518
  • 52
  • 313
  • 390