snippetpythonCriticalCanonical
How do I create a constant in Python?
Viewed 0 times
constanthowpythoncreate
Problem
How do I declare a constant in Python?
In Java, we do:
In Java, we do:
public static final String CONST_NAME = "Name";
Solution
You cannot declare a variable or value as constant in Python.
To indicate to programmers that a variable is a constant, one usually writes it in upper case:
To raise exceptions when constants are changed, see Constants in Python by Alex Martelli. Note that this is not commonly used in practice.
As of Python 3.8, there's a
To indicate to programmers that a variable is a constant, one usually writes it in upper case:
CONST_NAME = "Name"To raise exceptions when constants are changed, see Constants in Python by Alex Martelli. Note that this is not commonly used in practice.
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[int] = 1
# Executes fine, but mypy will report an error if you run mypy on this:
a = 2Code Snippets
CONST_NAME = "Name"from typing import Final
a: Final[int] = 1
# Executes fine, but mypy will report an error if you run mypy on this:
a = 2Context
Stack Overflow Q#2682745, score: 1441
Revisions (0)
No revisions yet.