Generating a stub class
Gerson Kurz
gerson.kurz at t-online.de
Thu Dec 5 09:27:21 EST 2002
I had some problems creating a dynamic stub class, but finally managed
to find a way. I was wondering if there is a more pythonic way to
achive the result.
------------(snip here)------------
# my interface definition
class myinterface:
def foo(self, arg1, arg2, arg3):
print "foo() called given %s, %s, %s" % (arg1, arg2, arg3)
def bar(self):
print "bar() called"
# generic stub class
class genericstub:
pass
# create stub for my interface definition
stub = genericstub()
for method in dir(myinterface):
# skip hidden methods
if method[0] <> '_':
def instance_method(*args):
print "%s called given %s" % (method, args)
setattr( stub, method, instance_method )
# check if stub works
stub.foo(1,2,3)
stub.bar()
------------(snip here)------------
This code won't work as (I) expected. It will result in
foo called given (1, 2, 3)
foo called given ()
because, as I understand it, the "method" inside "instance_method" is
a reference to the loop variable "method" used during the generation
of the stub class.
My solution is creating a "method class" like this:
class instance_method:
def __init__(self, methodname):
self.methodname = methodname
def __call__(self, *args):
print "%s called given %s" % (self.methodname, args)
which works just fine. Is there an easier solution than that?
More information about the Python-list
mailing list