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
There is not a keyword to do this. There are workarounds (such as the mutable default argument), but there are better ways to achieve the same thing.
For exaple you could set the variable as a function attribute:
def my_func():
my_func.my_list.append(1)
my_func.my_list = []
However this is just a hacky way of doing this:
class MyFuncFactory:
def __init__(self):
self.my_list = []
def __call__(self):
self.my_list.append(1)
Hence you are probably better of writing a class instead of a function in this case.
Sometimes you could use a nonlocal
variable. For example to define a key
function which requires state I usually write something like:
def my_key_builder():
some_state = 0
def key_function(arg):
nonlocal some_state
some_state += 1
return some_state % 2
return key_function
for x in sorted(a_list, key=my_key_builder()):
print(x)
Using a nonlocal
instead of a global
(or mutable default argument) allows you to use the key function multiple times. However if the function becomes slightly bigger using a class is probably the best option.