Question
Answer and Explanation
The keyword const
, which is commonly used in languages like JavaScript, C++, and C, does not exist as a reserved keyword in Python. Python does not have built-in language-level support for declaring constants in the way that these other languages do.
However, the concept of constants is still relevant in Python programming, and there are best practices and conventions for representing them. In Python, the common approach to representing a constant is to define a variable with all capital letters. For example:
MY_CONSTANT = 10
PI = 3.14159
GREETING = "Hello, World!"
While this convention signals to other developers that this variable is intended to be a constant, Python does not enforce immutability. You can still modify this value later in your code if you choose, although it's not considered good practice.
To truly achieve constant-like behavior (though still not foolproof), you might consider using properties or classes to encapsulate and protect constant values. Below is an example using properties:
class Constants:
@property
def MY_CONSTANT(self):
return 10
consts = Constants()
print(consts.MY_CONSTANT) #Output 10
In the example above, the MY_CONSTANT
is read-only from an external view, although it still isn't truly immutable.
In conclusion, Python lacks a native "const" keyword, so we use naming conventions and properties to represent constants and protect against accidental modifications.