static variables in Python?

pigmartian scottpig1 at comcast.net
Wed Jul 30 03:38:01 CEST 2008


bearophileHUGS at lycos.com wrote:
> kj:
>> OK, I guess that in Python the only way to do what I want to do
>> is with objects...
> 
> There are other ways, like assigning the value out of the function,
> because Python functions too are objects:
> 
...
> But I suggest you to use a class in this situation, it's often the way
> that will keep your code more bug-free, and more readable by near-
> casual readers too. Python philosophy asks you to write readable code
> instead of clever code when possible, this is a difference from Perl,
> I presume.
> 
> Bye,
> bearophile

Here's a solution using decorators, I like it, but I'm biased:

def staticAttrs(**kwds):
	"""
	Adds attributes to a function, akin to c-style
	"static" variables
	"""
	
	def _decorator(fcn):
		for k in kwds:
			setattr(fcn, k, kwds[k])
		return fcn
	return _decorator



@staticAttrs(n=0)
def rememberCalls():
	"""
	>>> rememberCalls()
	0
	>>> rememberCalls()
	1
	>>> rememberCalls()
	2
	"""
	print rememberCalls.n
	rememberCalls.n += 1

~Scott



More information about the Python-list mailing list