access the name of my method inside it

Paul McGuire ptmcg at austin.rr.com
Wed Aug 1 09:18:53 EDT 2007


On Aug 1, 8:07 am, james_027 <cai.hai... at gmail.com> wrote:
> Hi,
>
> On Aug 1, 5:18 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>
> > On Wed, 01 Aug 2007 09:06:42 +0000, james_027 wrote:
> > > for example I have this method
>
> > > def my_method():
> > >     # do something
>
> > >     # how do I get the name of this method which is my_method here?
>
> > Why do you need this?  There are ways but those are not really good for
> > production code.
>
> I am going to use this in Django. I am trying to implement a
> permission here, where in the database store the methods that the user
> are allowed to execute. for example if the method is def
> create_event(): the method will look for create_event in the database
> to see if it allow to be execute.
>
> Thanks.
> james

How about using a decorator?  Here is a rough version:

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)

-- Paul





More information about the Python-list mailing list