How to make a valuable immutable in python?

if I create a variable x and assign it a value say 7 i.e. x=7. I can again assign a value x=8. And this will continue. So I wish to restrict it to first assignment. How do I do this?

14th Apr 2019, 10:31 AM
random moments
random moments - avatar
2 Answers
+ 6
There are no constants in python. You can create a class and declare an instance variable as a read-only property: class Const(): def __init__(self, val): self._val = val @property def val(self): return self._val c = Const(5) print(c.val) # 5 c.val = 85 # error: can't set attribute But even that won't prevent you from just reassigning a whole different type/value to your "constant": c = 'hi' # no problem
14th Apr 2019, 10:52 AM
Anna - avatar
+ 1
You could use a tuple instead... It would look something like this: x = (7,) tuples are immutable, but unfortunately they can still be overwritten...so this would not help in your case :/
14th Apr 2019, 10:48 AM
Marcin Szcz
Marcin Szcz - avatar