Assuming:
def myfunc(x):
my_list = []
list.append(x)
is there a keyword to stop a variable(my_list) from being reassigned? Let's suppose that NA is the keyword:
def myfunc(x):
NA listv = []
list.append(x)
in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!
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:
However this is just a hacky way of doing this:
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 akey
function which requires state I usually write something like:Using a
nonlocal
instead of aglobal
(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.You can declare the variable globally as in C/C++ and use global keyword in python to refer them as variable in global data section. Some of references about them:
https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python
http://www.geeksforgeeks.org/global-local-variables-python/
Use of "global" keyword in Python
I believe the behaviour you're seeking is almost exactly how mutable default arguments work in python: instantiated only during function definition.
The
*args
will protect the list from being overwritten by an erroneously passed second argument.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.
Or in the case of your variable (haven't tested it)