Malonge
Malonge

Reputation: 2040

What Qualifies as Global Constants in Python

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?

Upvotes: 0

Views: 1118

Answers (2)

hspandher
hspandher

Reputation: 16733

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.

Upvotes: 0

Martin
Martin

Reputation: 1069

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.

Upvotes: 2

Related Questions