How can I programmatically find the name of a method from within that method?

kj7ny kj7ny at nakore.com
Wed Aug 8 03:16:24 EDT 2007


On Aug 7, 10:09 pm, Jay Loden <pyt... at jayloden.com> wrote:
> kj7ny wrote:
> > Is there a way that I can programmatically find the name of a method I
> > have created from within that method?  I would like to be able to log
> > a message from within that method (def) and I would like to include
> > the name of the method from which it was written without having to
> > hard-code that value in every message string.  While we're at it, is
> > there a way to programmatically get the name of the class and the
> > module while I'm at it?
>
> This is a frequently asked question around here :-)
>
> You should search the list archives for past threads, e.g:http://aspn.activestate.com/ASPN/Mail/Message/python-list/3542665
>
> -Jay

Thanks for the link.  I had actually searched the past threads, but
apparently didn't enter the right search criteria because I did not
find that thread.  Or, that thread isn't findable by searching Google
groups?

I tried the example in the interpreter and it appears to work.
Despite my years and years of programming in python, I am a bit
baffled by the example though.  What is @checkPrivs (see example
copied below from other post)?  In fact... how does the thing work at
all?

------------------------------------------
def checkPrivs(fn):
    fnName = fn.func_name
    def restricted(*args):
        print "about to call function", fnName
        if fnName in listOfAllowedFunctions:
            return fn(*args)
        else:
            raise KeyError("you don't have sufficient privileges to do
THAT")
    return restricted

listOfAllowedFunctions = ['add','subtract']

@checkPrivs
def add(a,b):
    return a+b

@checkPrivs
def subtract(a,b):
    return a-b

@checkPrivs
def multiply(a,b):
    return a*b

add(1,2)
subtract(4,1)
multiply(3,2)




More information about the Python-list mailing list