Equiv of C's static local vars in Py ?

Ben Wolfson wolfson at uchicago.edu
Sun Dec 1 19:31:16 EST 2002


On Sun, 01 Dec 2002 14:28:09 +0000, Erik Max Francis wrote:

> Az Tech wrote:
> 
>> This function f retains the value of call_count between successive
>> calls to it - so each time it is called, the value for call_count
>> printed out will be one more than the last one.
>> 
>> Can this be done in Python and if so, how ?
> 
> This was just asked and answered a few days ago.  Python doesn't have
> any notion of a static variable in the sense that you mean here.  If you
> want, you can simply use a global:
> 
> 	_Count = 0
> 	def f():
> 	    global _Count
> 	    _Count += 1
> 	    print "f been called %d times" % _Count

I didn't read the other threads on this subject, but recent Pythons have
what I think is a more graceful way:

>>> def f():
	f.count += 1
	print 'f has been called %d times' % (f.count)

	
>>> f.count = 0
>>> f()
f has been called 1 times
>>> f()
f has been called 2 times
>>> 

You still have to initialize the variable outside the function-definition
block, but it's more obviously intended to go with that function alone.

-- 
I certainly seem to be enjoying myself in the same way, smacking my
lips, sighing and moaning, dripping [REDACTED] on my shirt and
smearing it into my moustache ... But ... If I snuck a lick of your
cone, I wouldn't smack my lips. -- Ted Cohen




More information about the Python-list mailing list