How do I declare a constant in Python? In Java, we do: public static final String CONST_NAME = "Name";
In Python, you can create constants using uppercase variable names by convention, although it's important to note that Python doesn't have true constants like some other languages. Conventionally, uppercase variable names are used to indicate that a variable should be treated as a constant and not changed, but the language itself doesn't prevent you from modifying them. Here's how you can declare a "constant" in Python:
python
CONST_NAME = "Name"
print(CONST_NAME)
In the example above, CONST_NAME is declared using uppercase letters to indicate that it's intended to be a constant. However, it's important to be aware that Python doesn't prevent you from reassigning the value of CONST_NAME elsewhere in your code.
If you want to create a value that truly cannot be changed, you can use the readonly feature from Python's dataclasses module, introduced in Python 3.7:
python
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Constants:
CONST_NAME: str = "Name"
constants = Constants()
print(constants.CONST_NAME)
In this example, the frozen=True argument in the @dataclass decorator ensures that the attributes of the class cannot be modified after initialization, effectively creating something closer to a true constant.
However, even with the frozen feature, it's important to note that it only affects the direct attributes of the class. If you have mutable objects as attributes, they can still be modified.
python
CONST_NAME = "Name"
print(CONST_NAME)
In the example above, CONST_NAME is declared using uppercase letters to indicate that it's intended to be a constant. However, it's important to be aware that Python doesn't prevent you from reassigning the value of CONST_NAME elsewhere in your code.
If you want to create a value that truly cannot be changed, you can use the readonly feature from Python's dataclasses module, introduced in Python 3.7:
python
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Constants:
CONST_NAME: str = "Name"
constants = Constants()
print(constants.CONST_NAME)
In this example, the frozen=True argument in the @dataclass decorator ensures that the attributes of the class cannot be modified after initialization, effectively creating something closer to a true constant.
However, even with the frozen feature, it's important to note that it only affects the direct attributes of the class. If you have mutable objects as attributes, they can still be modified.
Comments
Post a Comment