Using Decorators

Updated dx135 2 Tallied Votes 508 Views Share

You can use a decorator to modify the function object once, by assigning initial values to some new attributes. Then use these attributes as you would use static variables in other languages.


Here is the result:
(1, 1, [1])
(3, 2, [1, 2])
(6, 6, [1, 2, 3])
(10, 24, [1, 2, 3, 4])

It works fine in Python 2.6 and 3.0.
Hope this helps.

TrustyTony commented: nice way to separate initialization of static variables from real parameters +13
def static_vars(**kwargs):
	"""Decorator for creating function object attributes"""
	def T(f):
		f.__dict__.update(kwargs)
		return f
	return T
	
@static_vars(s=0, p=1, cache=[])
def my_func(x):
	my_func.cache.append(x)
	my_func.s += x
	my_func.p *= x
	return my_func.s, my_func.p, my_func.cache

print(my_func(1))
print(my_func(2))
print(my_func(3))
print(my_func(4))