0

How to create constants in Python?

Why there are no constants in python?

14th Apr 2018, 6:54 PM
Alihuseyn Kengerli
Alihuseyn Kengerli - avatar
4 Answers
+ 4
you cannot declare a variable constant in python, but it is possible to create a property that has a "getter function" to read and manipulate the data, but no "setter function" to re-write and change the data. This will prevent the identifier from being changed.
14th Apr 2018, 6:57 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 2
You can also define a constant inside a tupel, which can not be changed. pi = (3.14159)
14th Apr 2018, 7:32 PM
Sebastian Keßler
Sebastian Keßler - avatar
+ 1
Sebastian Keßler Well, this is not a tuple. Then, you can not modify a variable inside a tuple, but you can redefine the tuple itself. So, your solution is not working.
14th Apr 2018, 11:32 PM
strawdog
strawdog - avatar
+ 1
Alihuseyn Kengerli There is no way to declare a constant in python. Even declaring a private attribute or method of a class is more a convention then a statement. But there is a "hack" that allowed you to make a kind of a constant as described here: http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991
14th Apr 2018, 11:38 PM
strawdog
strawdog - avatar