def h1 (y = []) :
assert(type(y) is types.ListType)
y += [2]
return y
Now, if I were to make these two calls:
h = h1()
h = h1()
h
would be equal to [2, 2]
This mutable default array lives on as a sort of memory for the function, which isn't exactly what I would have expected.
Now, if I were to make another call to
h1([1])
with an argument, the default array gets wiped away. To be clear, at the end of this sequence of statements:
h = h1()
h = h1()
h = h1([1])
h
now equals [1, 2]
and one final call:
h = h1()
results in
h
equal to [2, 2, 2]
So it seems that the persistent array is actually persistent and surfaces any time an argument isn't give.
Although this strange behaviour might introduce a bug into an unsuspecting programmer's function, it can also be a very attractive way of giving a function some persistent storage...possibly a useful feature if you wanted to write something like a primes generator.
No comments:
Post a Comment