access the name of my method inside it

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Aug 1 16:38:31 EDT 2007


Cousin Stanley a écrit :
>>>>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.
> 
> 
> james .... 
> 
>   Perhaps a simple-minded hard-coded solution
>   might work .... 
> 
>      def permission_check( name ) : 
> 
>          permission = DB.permission_check( name )
>  
>          if not permission : 
> 
>              print 'No Execute Permission for %s ' % name
> 
>              sys.exit( -1 )

An exception would be better here.

>     def my_method() : 
> 
>         permission_check( "my_method" )
> 
>         ....
> 

May I suggest ?

class Unauthorized(Exception): pass

def check_permission(permission):
   if not DB.check_permission(permission):
     raise Unauthorized(permission)

def requires_perm(func):
   def with_check(*args, **kw):
     check_permission(func.__name__)
     return func(*args, **kw)
   return with_check

@requires_perm
def my_method():
    # do something useful here



More information about the Python-list mailing list