Data

Constant

Python

 

Defining Constant

Python 2.7
def constant(f):
    def fset(self, value):
        raise TypeError
    def fget(self):
        return f()
    return property(fget, fset)

class constants(object):
    @constant
    def PI():
        return 3.14

    @constant
    def E():
        _CONST = constants()
        return (_CONST.PI**4 + _CONST.PI**5)**(1.0/6)
      
CONST = constants()

There is no native support for Constants in Python.

Here we are mimicking the constant behavior by defining getters and throwing an error on setters access.

print(CONST.PI)   # 3.14
print(CONST.E)    # 2.7171888402596216

CONST.PI = 2.12   # Error
 

Getting Constant value

Python 2.7
# Assume that we have defined PI and E in the previous card

r = 2;
area = r * r * CONST.PI;   # area -> 12.56

By defining PI like in the previous card, you can access its value simply by using its name on the CONST object.