Assuming:
def myfunc(x):
my_list = []
list.append(x)
is there a keyword to stop a variable(my_list) from being reassigned? Let\'s supp
I guess you are looking for something equivalent to the final
keyword in Java. Simply put, there is no such keyword. The Python attitude is "if you don't want this modified at all, just don't modify it, I wont stop you though".
However you can mimic something like it by some tweaks in your class.
class MyFinalVariablesClass:
def __setattr__(self, attr, value):
# if it already has this attribute, complain !
if hasattr(self, attr):
raise Exception("Attempting to alter read-only value")
self.__dict__[attr] = value
Or in the case of your variable (haven't tested it)
class WriteOnceReadWhenever:
def __setattr__(self, attr, value):
if attr == 'my_list' and hasattr(self, attr):
raise Exception("Attempting to alter read-only value")
self.__dict__[attr] = value