Menu Close

How to create a constant in Python?

Sometimes, we want to create a constant in Python.

In this article, we’ll look at how to create a constant in Python.

How to create a constant in Python?

To create a constant in Python, we can use the typing.Final property.

For instance, we write

from typing import Final

a: Final = 1

to set variable a to the Final type.

This will be checked by static type checkers to see if a has been reassigned.

But it doesn’t prevent reassignment at run time.

Conclusion

To create a constant in Python, we can use the typing.Final property.

Posted in Python, Python Answers