Accessing a method from within its own code

Paddy O'Loughlin patrick.oloughlin at gmail.com
Mon Nov 2 14:28:02 CET 2009


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 (I am aware
that regexp objects are cached, avoiding this problem, but I'm just using
this as an example for what I want to know), so I've added it to the method
object as an attribute and create it only if it doesn't exist.

However, typing out <Classname>.<MethodName>.<variablename> everytime is
pretty long and susceptible to refactoring issues, so I was wondering if
there was a way in Python that I am missing which allows you to reference
the method that the code is in (like __module__ gives a reference to the
parent module).

Paddy

-- 
"Ray, when someone asks you if you're a god, you say YES!"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091102/a5bf66fe/attachment.html>


More information about the Python-list mailing list