[PEAK] interfaces as factory?

Tracy S. Ruggles tracer at axiomfire.com
Thu Jun 17 19:20:15 EDT 2004


Hi all,

I'm a pretty solid user of the PyProtocols package and came across this 
option as a way of creating/adapting objects to an interface.  Is it a 
bad thing to do, and, if so, why?  (see the __new__ method in the 
BaseInterface class)


# --- example ---

import types
import protocols

class BaseInterface(protocols.Interface):
	def __new__(klass, obj):
		return protocols.adapt(obj, klass)

class IThing(BaseInterface):
	'''I'm a simple doer of things'''
	def doMyThing(arg):
		'''do my thing with the arg'''

class StringAsThing(object):
	protocols.advise(instancesProvide=[IThing], asAdapterForTypes=[str])
	def __init__(self, obj, protocol=None):
		self.obj = obj
	def doMyThing(self, arg):
		return self.obj % arg

class FunctionAsThing(object):
	'''assuming this function takes one arg and return a formatted 
string...'''
	protocols.advise(instancesProvide=[IThing], 
asAdapterForTypes=[types.FunctionType])
	def __init__(self, obj, protocol=None):
		self.obj = obj
	def doMyThing(self, arg):
		return self.obj(arg)

def sample(obj,  arg):
#	adapter = protocols.adapt(obj, IThing)
	adapter = IThing(obj)
	return adapter.doMyThing(arg)

if __name__ == '__main__':
	a = "this is my value: %s"
	b = lambda arg: "this is my value: " + str(arg)
	for test in (a,b):
		print sample(test, "super dooper")

# ---  end example  ---

Thanks!
--Tracy




More information about the PEAK mailing list