I want to keep astructure saved over iterations of a function, in order to keep data to use it for later purpose.
There is a simple way to do it, in using a global variable.
The thing is, anyone could access the variable.
So, is there a way to create a variable accessing only by the function, but that would not be erased when running this function?
Ex :
mylist = []
def test():
global mylist
if mylist:
my_list.append(1)
other_stuff, using my_list
Is exactly what I want to do, but my_list could be accessed by anyone else.
(ok I know, the example is completely dumb)
Sorry for the formulation, but I could not come with something simpler
EDIT : Ok, so with so different (and all interesting) solutions. I’ll quickly explain the idea of what I want to do 🙂
Let’s imagine I want to calculate is a number is a prime. This is usually computationnaly coslty.
So I got a is_prime(value) function, returning False or True.
value can be any number, but there are chances (in my case) that value takes several times the same value (litteraly ^^).
In this case, I could use a (not to long ) list of primes I have already found to quickly check and save computations.
But my prime_list is no use in a function returning true/false.
So here is my question :).
Hope to clarify some minds (including me! ).
Here is a case where a list as the default value of a parameter can come in handy:
I leave the
if myListoff, since it will exist (it was created whentestwas defined). (Plus,if myListtests if the list is non-empty, not defined).myList, as a function parameter, is local totest. Whentestis defined, it is initialized to a list. The value of the list persists for the life of your program.Compare to the standard advice of
which is necessary when you want a fresh empty list inside
testat each call if no list is provided by the call.