Define constant in Python


How can I declare a constant in Python the same way I do in C with

#Define PI 3.1415

or in java

public final double PI = 3.1415


In Python (in versions lower than 3.8) this is not possible. Just create a variable and don't change its value.

PI = 3.1415

This second option would not have the same effect as a constant, as it is possible to rewrite a function elsewhere in the code.

A simple workaround , if it really is very necessary to have total guarantee that this value will never be rewritten in another part of the code, is to create a function that returns the desired value.

def const_pi():
    return 3.1415

Scroll to Top