How do I create a constant in Python?

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 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 = 2

Leave a Comment