[Tutor] C-like local static var in Py ?

Bob Gailer ramrom@earthling.net
Sun Dec 1 21:36:00 2002


At 12:07 AM 12/2/2002 +0100, Yann Le Du wrote:

>def inc(v=[0]):
>         v[0]+=1
>         print v[0]
>
>First time you call inc(), it will print 1, then 2, etc...

This is an interesting side effect of the fact that a function evaluates 
its argument defaults only once. This creates in essence an anonymous list 
in the global environment, which can be operated on only within the 
function. Hoo boy.

>You can reset this by setting v=[0] outside of that function.

No; that does not work. This creates a global variable v that is 
independent of the one in inc. However this will work:

v2 = [0]
def inc(v = v2):
# rest the same

You can then reset things by resetting v2[0]. Note that if you set v2 = 0 
you create a new list assigned to v2; the original list still remains 
associated with the function default.

If one adds print id(v) to inc one sees, as expected, the same number 
(address of the object) each time. Is there some way in Python, given such 
an id, to access the object at that address?

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625