0

I am just trying to become familiar with the proper terminology.

What data structures can be global constants? Do they have to be immutable data structures?

For example, I know this would be a global constant:

THIS_CONSTANT = 5

But, for example, can a list be a constant? Provided it doesn't change throughout the program, even though it is a mutable data type?

LIST_CONSTANT = [1, 2, 3, 4]

Another way of asking my question is, is it proper to use mutable datatypes as global constants?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Malonge
  • 1,980
  • 5
  • 23
  • 33
  • possibly duplicate: http://stackoverflow.com/questions/2682745/creating-constant-in-python – mission.liao Aug 03 '15 at 05:12
  • 1
    Yeah that basically answers my question, though I am really asking about convention, not what is technically allowed. – Malonge Aug 03 '15 at 05:15
  • From the other question: http://stackoverflow.com/a/2683099/2864740 – user2864740 Aug 03 '15 at 05:18
  • 1
    I think the message conveyed by using capital letters would be both that the variable will/should not be assigned to and that the object it refers to or any indirectly reffered will not be modified. You can have it be a list, but since you should not change it, it could as well be a tuple. For other datatypes you don't have the opportunity to use non-mutable equivalent - so yes it's OK. – skyking Aug 03 '15 at 05:45

2 Answers2

2

From experience (no sources): yes. As long as you don't change the value throughout the program, I would say it's allowed to be a global constant. The code style is a message for yourself and other programmers saying this variable's value will never change.

EDIT:

As @NightShadeQueen noted, using a tuple would be better, because it is immutable. This will help you not to (accidentally) change your constant's value.

Martin
  • 967
  • 1
  • 6
  • 17
  • 2
    Hum. I think, in this case, I'd still would rather go with a tuple instead of a list, a frozenset instead of a set, a frozen dictionary instead of a dictionary, etc, and only use a mutable type if I had no other choice. – NightShadeQueen Aug 03 '15 at 09:16
  • I didn't know a frozen dictionairy existed. Could you link the docs? – Martin Aug 11 '15 at 08:29
  • Derp. There isn't one, I don't know why I thought there was one. – NightShadeQueen Aug 11 '15 at 12:50
0

Well, Although you should prefer to use class variables/constants instead of global variables, global constants are not inherently bad. Real problems arise when you begin to mutate them. So, if global constants you are using are immutable then you need not to worry about a thing. But, if your global constants are mutable then you need to ensure that in no way you can be modifying them on runtime.

hspandher
  • 15,934
  • 2
  • 32
  • 45