Often Python is referred to as flexible and easy to learn programming language, mostly this is because it lacks some of the features you normally don't need that much. One of those features is const objects: being able to protect a variable against future change. Some languages call this "final", others "const", here is the best way I could think of to do this in Python:
import contextlib
@contextlib.contextmanager
def constant(vars):
''' Protect the return values of (callable) vars from change
Use:
def f():
def constants():
return a,b
a=12
b=24
with constant(constants):
print 'Do something'
#If you would use b=2309 it will raise an exception after the with block.
'''
__protection_information = [(id(i), hash(i)) for i in vars()]
yield
for i, v in enumerate(vars()):
pi = __protection_information[i]
if not pi[0] == id(v):
raise Exception('id() of const variable %i changed' % i)
if not pi[1] == hash(v):
raise Exception('hash() of const variable %i changed' % i)Then use it as:
def a():
def constants():
return this_variable, that_variable
this_variable = 20
that_variable = 30
with constant(constants):
#In this block you are not allowed to change this_variable or that_variable, they are effectively const (will raise and error if they are changed after the block
#this_variable = 329 #Would raise an error (at the end of the with block) if you did this.
#At this point you know that this_variable and that_variable are both still 20 and 30.Not the best solution out there, and nothing like having language support for something like this, but it works.