Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a constant 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?

like image 501
zfranciscus Avatar asked Apr 21 '10 12:04

zfranciscus


People also ask

What is a constant in Python example?

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.

How do you declare a constant?

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.

Is there is constant variable in Python?

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.


1 Answers

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 
like image 196
Felix Kling Avatar answered Sep 24 '22 01:09

Felix Kling