954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Using Decorators

By dx135 on Jun 1st, 2011 1:07 pm

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.

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))

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You