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

David Hirschfield davidh at ilm.com
Tue Jun 30 21:14:11 EDT 2009


Unfortunately that still requires two separate decorators, when I was 
hoping there was a way to determine if I was handed a function or method 
from within the same decorator.

Seems like there really isn't, so two decorators is the way to go.
Thanks,
-David

Carl Banks wrote:
> 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
>   

-- 
Presenting:
mediocre nebula.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090630/1d8df313/attachment-0001.html>


More information about the Python-list mailing list