Synchronizing methods of a class

Keith Veleba keith.veleba at gmail.com
Mon Feb 7 14:57:02 EST 2005


Hello to all fellow c.l.p'ers!

Long-time listener, first-time caller.

Background:
I'm working on a project where I have to do some serious
multithreading. I've worked up a decorator in Python 2.3.4 to implement
the lock semantics required for specific functions I want to
synchronize:

def synchronized(method):
	def f(*args,**kwargs):
		self = args[0]
		self._lock.acquire();
		try:
			return method(*args,**kwargs)
		finally:
			self._lock.release()
	return f

And a convenience method to synchronize all methods of a given class:

def synchronize(klass, allow=None, deny=None):
	"""Synchronize methods in the given class
	Only synchronize the methods whose names are
	not in the deny list,in the allow list, or all methods if allow and
deny are not specified.."""
	if deny is None: deny=[]
	deny.append('__init__')
	for (name, val) in klass.__dict__.items():
		print "attr '%s':" % (name),
		if callable(val):
			if name not in deny:
				if allow is None or name in allow:
					klass.__dict__[name] = synchronized(val)
					print "synchronized."
				else:
					print "not synchronizing, name not in allow list" % name
			else:
				print "not synchronizing, name in deny list."
		else:
			print "not synchronizing, not callable."
	return klass

Obviously, my classes have to instantiate the _lock in __init__ in
order for this to work.

Problem:

When iterating through klass.__dict__.items() in the convenience
method, I only get the instance variables of the class.  No functions.
I've found a way to get the function list, by iterating through
klass.__class__.__dict__ .

My Question:

If I decorate these function references in __class__.__dict__, am I
doing it only for my specific instance of that class or the base class
as well? 

Thanks in advance,
Keith Veleba




More information about the Python-list mailing list