Constants in Python

Author
By Darío Rivera
Posted On in Python

In Python, a constant is a name that refers to a value you intend not to change throughout your program. Unlike some languages (like C or Java), Python does not have built-in constant types, which means you can always re-assign any name, but the community follows conventions that make code clearer and easier to maintain.

Let's take a look at the following example.

PI = 3.14159
MAX_CONNECTIONS = 100

Here, PI and MAX_CONNECTIONS are constants by convention. We use all capital letters so other developers know these values should not change.

It is common to group all constants in a single file in Python. Given the file constants.py with the contents exposed above, the following will be the way to import those constants in another module.

from constants import PI, MAX_CONNECTIONS

print(PI, MAX_CONNECTIONS)

Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.