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?
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?
You can emulate constant variables with help of the next class. An example of usage:
Call the constructor when you want to start a new constant namespace. Note that the class is under protection from unexpected modifying sequence type constants when Martelli's const class is not.
The source is below.
A tuple technically qualifies as a constant, as a tuple will raise an error if you try to change one of its values. If you want to declare a tuple with one value, then place a comma after its only value, like this:
To check this variable's value, use something similar to this:
If you attempt to change this value, an error will be raised.
Unfortunately the Python has no constants so yet and it is shame. ES6 already added support constants to JavaScript (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/const) since it is a very useful thing in any programming language. As answered in other answers in Python community use the convention - user uppercase variable as constants, but it does not protect against arbitrary errors in code. If you like, you may be found useful a single-file solution as next (see docstrings how use it).
file constants.py
If this is not enough, see full testcase for it.
Advantages: 1. Access to all constants for whole project 2. Strict control for values of constants
Lacks: 1. Not support for custom types and the type 'dict'
Notes:
Tested with Python3.4 and Python3.5 (I am use the 'tox' for it)
Testing environment:
.
Here's a trick if you want constants and don't care their values:
Just define empty classes.
e.g:
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:
if not, it is just
But you might want to have a look at the code snippet Constants in Python by Alex Martelli.
The Pythonic way of declaring "constants" is basically a module level variable:
And then write your classes or functions. Since constants are almost always integers, and they are also immutable in Python, you have a very little chance of altering it.
Unless, of course, if you explicitly set
RED = 2
.