0

This question was marked as duplicate of another question. I am not asking how to create enumerations, I'm asking how to create constants, and that is the difference between the questions.

This question was marked as duplicate of yet another question. While the answers do explain how to create constants in python they don't explain how to create them in Enum like style, which is what my question is asking for.

I need to create constants in my python code. I don't want the user to be able to modify them. I found this, but it is not exactly what I need. I need to be be able to use them just like enums, without creating and instance.

For example:

class MyConstClass(object):
    Const0 = 0
    Const1 = 1
    Const2 = 2

myfunc(MyConstClass.Const0)
MyConstClass.Const1 = 20 # Raise an exception

I also don't want to create a module, just like it is done here

Is there a way to do it?

12
  • 2
    In Python, everything can be modified. Rather than try to lock this down, trust the developer. Commented Nov 8, 2016 at 22:36
  • "I need to create constants in my python code. I don't want the user to be able to modify them." - essentially impossible, and not worth trying. Commented Nov 8, 2016 at 22:36
  • code.activestate.com/recipes/65207-constants-in-python/… Commented Nov 8, 2016 at 22:41
  • If you really want and/or must do that, you shouldn't be using Python at all, as this goes against Python ideology. That's not Pythonic at all. Commented Nov 8, 2016 at 23:02
  • 2
    Philosophical questions are off-topic on stackoverflow. An Enum is suitable for the use-case you've described. Commented Nov 9, 2016 at 1:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.