Accessing a method from within its own code

Dave Angel davea at ieee.org
Mon Nov 2 16:21:46 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 (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
>
>   
I suspect that the "inspection" module has your answer, but that it'll 
be bulkier, and much slower than just doing what you're doing already.

Why not use the default arguments gimmick?  Since this cached item is to 
have a module lifetime, it'd be desirable to create it when the method 
is being defined, which is exactly what default arguments do.

Something like (untested):

class ...
    def find_line(self, lines, _cacheitems = [] )
        if not _cacheitems:
            _cacheitems.append(    re.compile.....   )
        for ...
            m = _cacheitems[0]( line )


DaveA




More information about the Python-list mailing list