I'm having a little problem with some python metaprogramming. I want to have a decorator which I can use either with functions or methods of classes, which will allow me to swap one function or method for another. It works as I want it to, except that I want to be able to do some things a little differently depending on whether I'm swapping two functions, or two methods of a class.

Trouble is, it appears that when the decorator is called the function is not yet bound to an instance, so no matter whether it's a method or function, it looks the same to the decorator.

This simple example illustrates the problem:

import inspect
class swapWith(object):
   def __init__(self, replacement):
       self.replacement = replacement
def __call__(self, thingToReplace):
       def _replacer(*args, **kws):
           import inspect
print "replacing:",self.replacement,inspect.ismethod(self.replacement)
           return self.replacement(*args, **kws)
       return _replacer

class MyClass(object):
def swapIn(self):
       print "this method will be swapped in"

   @swapWith(swapIn)
   def swapOut(self):
       print "this method will be swapped out"

c = MyClass()
c.swapOut()


def swapInFn():
   print "this function will be swapped in"
@swapWith(swapInFn)
def swapOutFn():
   print "this function will be swapped out"

swapOutFn()


Both MyClass.swapIn and swapInFn look like the same thing to the decorator, and MyClass.swapOut and swapOutFn look the same. So is there a pattern I can follow that will allow me to determine whether the objects I'm given are plain functions or belong to a class?

Thanks in advance,
-David

--
Presenting:
mediocre nebula.


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to