Accessing a method from within its own code

Gerard Flanagan grflanagan at gmail.com
Mon Nov 2 16:29:26 CET 2009


Paddy O'Loughlin wrote:
> Hi,
> I was wondering if there was a shorthand way to get a reference to a 
> method object from within that method's code.
> 
> Take this code snippet as an example:
> import re
> 
> class MyClass(object):
>     def find_line(self, lines):
>         if not hasattr(MyClass.do_work, "matcher"):
>             MyClass.do_work.matcher = re.compile("\d - (.+)")
>         for line in lines:
>             m = MyClass.do_work.matcher.match(line)
>             if m:
>                 return m.groups()
> 
> Here, I have a method which uses a regular expression object to find 
> matches. I want the regexp object to be tied to the function, but I 
> don't want to have to recreate it every time the function is called

Just an idea:

------------------------------
import re

def matches(patt):
     def wrapper(fn):
         def inner(self, *args, **kw):
             return fn(self, *args, **kw)
         inner.match = re.compile(patt).match
         return inner
     return wrapper

class MyClass(object):

     @matches('ab(.*)')
     def func(self):
         print 'hi'
         return 5

c = MyClass()

ret = c.func()
print ret
print c.func.match('abc').groups()
------------------------------------





More information about the Python-list mailing list