Is there a way to declare a constant in Python? In Java we can create constant values in this manner:
public static final String CONST_NAME = "Name";
What is the equivalent of the above Java constant declaration in Python?
A constant is a type of variable that holds values, which cannot be changed. In reality, we rarely use constants in Python. Constants are usually declared and assigned on a different module/file.
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
Creating constant variables, functions, objects is allowed in languages like c++, Java. But in python creating constant variable, it is not allowed. There is no predefined type for a constant variable in Python.
No there is not. You cannot declare a variable or value as constant in Python. Just don't change it.
If you are in a class, the equivalent would be:
class Foo(object): CONST_NAME = "Name"
if not, it is just
CONST_NAME = "Name"
But you might want to have a look at the code snippet Constants in Python by Alex Martelli.
As of Python 3.8, there's a typing.Final
variable annotation that will tell static type checkers (like mypy) that your variable shouldn't be reassigned. This is the closest equivalent to Java's final
. However, it does not actually prevent reassignment:
from typing import Final a: Final = 1 # Executes fine, but mypy will report an error if you run mypy on this: a = 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With