what is the best way to define constant variables python 3

TomE8 picture TomE8 · May 25, 2018 · Viewed 55.3k times · Source

I am writing a program in python which contains many constant variables. I would like to create a file which will hold all these variables like .h file in C that contains many #define. I tried to use configparser however I didn't find it easy and fun to use.

Do you know a better way?

Answer

scharette picture scharette · May 25, 2018

Python does not allow constant declarations like C or C++.

Normally in Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.

Ex. MY_CONSTANT = "Whatever"

Another valid way of doing it which I don't use but heard of, is using a method:

def MY_CONSTANT():
    return "Whatever"

Now in theory, calling MY_CONSTANT() acts just like a constant.

EDIT

Like the comments says, someone can go and change the value by calling

MY_CONSTANT = lambda: 'Something else'

but don't forget the same person can call MY_CONSTANT = "Something else" in the first example and change the initial value. In both cases it is unlikely but possible.