Determining if a function is a method of a class within a decorator

Carl Banks pavlovevidence at gmail.com
Wed Jul 1 02:50:20 CEST 2009


On Jun 29, 6:01 pm, David Hirschfield <dav... at ilm.com> wrote:
> 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,



class HomemadeUnboundMethod(object):
    def __init__(self,func):
        self.func = func
    def __call__(self,*args,**kwargs):
        print "is a function: %s" % self.func.func_name
        return self.func(*args,**kwargs)
    def __get__(self,obj,owner):
        return HomemadeBoundMethod(obj,self.func)

class HomemadeBoundMethod(object):
    def __init__(self,obj,func):
        self.obj = obj
        self.func = func
    def __call__(self,*args,**kwargs):
        print "is a method: %s" % self.func.func_name
        return self.func(self.obj,*args,**kwargs)

class A(object):
    @HomemadeUnboundMethod
    def method(self): pass

@HomemadeUnboundMethod
def function(): pass

A().method()
function()



Just override the __call__ functions to do what you want the decorated
function to do.  There are other little improvements you might make
(account for the owner parameter of __get__ for instance) but you get
the idea.


Carl Banks



More information about the Python-list mailing list