Could you help me I have a doubt that there is a difference between variable and constant in the language of python
Could you help me I have a doubt that there is a difference between variable and constant in the language of python
A constant in Python will always be that declared variable that will not change its value during runtime. (It is declared in capital letters) Consult PEP8
Note: This theme of Python constants will be purely of writing styles. As such there is no such natural behavior in language as we could do in other languages.
A variable will be used as support for your operations and will change or change its value depending on the flows you manage in your programmed logic. (It is declared in lowercase.)
Now I give you some examples:
CONSTANT
You can create a file in python called settings.py and add variables like these:
CONFIG_URL_RESPONSE = "https://XXXXXX.XXX"
LOGIN_ATTEMPS = 2
MAX_UPLOAD = 100M
And then you can use them in the following way:
from . import settings
print(settings.CONFIG_URL_RESPONSE)
print(settings.LOGIN_ATTEMPS)
print(settings.MAX_UPLOAD)
VARIABLES
The variable will be used like this:
result = 0
num_1 = 2
num_2 = 3
result = num_1 + num_2
print(result)
As you can see, the variable result changed its value at runtime and will be able to change without problems as many times as necessary.
Note: It is important to mention that Python is a flexible language in the variable declaration topic. If a variable that is assumed to be constant is modified at runtime, the language will change it without presenting any errors. To avoid making changes to these constants, we can do a little trick by declaring a class with methods inside it and decorating them as constants. This is done as follows:
def is_constant(f):
def fset(self, value):
raise TypeError
def fget(self):
return f()
return property(fget, fset)
class SettingsClass:
@is_constant
def MAX_UPLOAD():
return 20
To use it you would do the following:
from settings import SettingsClass
sett = SettingsClass()
print(sett.MAX_UPLOAD)
sett.MAX_UPLOAD = 100 # <-- Aquí se generaría un error
print(sett.MAX_UPLOAD)
In Python, the concept of a constant does not exist as one could imagine it from the perspective of another language such as C . Let's see why:
First of all, what is a variable? In Python a variable is a reference to an object of some kind, an integer, a string, a list, a dictionary, etc. The important thing is that the variable is a reference and is not the object. Because of this, a reference can always be "reassignable", for example, I can declare HTTP_PORT = 80
and assume that HTTP_PORT
is a constant, but it is still a convention, HTTP_PORT
is a reference to an integer whose value is 80
, but in any place / moment I can reassign the variable / reference doing something like HTTP_PORT = 8080
and now HTTP_PORT
"points" to another whole object whose value is 8080
In short, there are no user constants in Python, yes, we can use as a convention that variables in uppercase are not reassigned and we use them as constant values, we are all adults and we know that we do not have to touch them. Notice that before I mentioned the "user constants", because Python does have certain own constants such as True
, False
, None
etc. More info .
There are alternatives to constants, for example, you can implement a class that allows you to configure its properties during initialization and not allow the modification of these later. For example here a very simple implementation.
class PyConstObj(object):
""" Implementation of a constant object in Python """
# --------------------------------------------------------------------------
def __init__(self, **kwargs):
for name, value in kwargs.items():
super(PyConstObj, self).__setattr__(name, value)
# --------------------------------------------------------------------------
def __setattr__(self, name, val):
""" When trying to set a new value to the constant object """
# If variable already exists in instance
if name in self.__dict__:
raise ValueError("Cannot change value of a constant")
else:
super(PyConstObj, self).__setattr__(name, val)
config = PyConstObj(HTTP_PORT=80, GOOGLE_URL="http://www.google.com")
print(config.HTTP_PORT)
print(config.GOOGLE_URL)
config.HTTP_PORT = 80
> 80
> http://www.google.com
> Traceback (most recent call last):
> File "python", line 22, in <module>
> File "python", line 13, in __setattr__
> ValueError: Cannot change value of a constant
Or even, much easier with the class namedtuple
import collections
constantes = collections.namedtuple('config', 'HTTP_PORT GOOGLE_URL')
config = constantes(HTTP_PORT=80, GOOGLE_URL="http://www.google.com")
print(config.HTTP_PORT)
print(config.GOOGLE_URL)
config.HTTP_PORT = 80
> 80
> http://www.google.com
> Traceback (most recent call last):
> File "python", line 10, in <module>
> AttributeError: can't set attribute