Question

My objective is to find the name of the file during a method execution. The main problem is I use a python decorator to transform a function. This decorator is in a separate file and being imported to the current file. I have explained the problem using a small scenario below:

Code Scenario

#Normal.py

import decorator

 class A:
    @entryExit
    def move(self):
        print "hello"    

a=A()
a.move()

#decorator.py
import sys
import inspect
def entryExit(f):
    def new_f(self,*args, **kwargs):
        File_Name=inspect.getfile(inspect.currentframe()).split("\\")
        print 'Entry',f.__name__,self.__class__.__name__,File_Name[-1]
        f(self,*args)        
        print 'Exit',f.__name__,self.__class__.__name__,File_Name[-1]        
    return new_f 

Actual Output:
Entry move A decorator.py
hello
Exit move A decorator.py

Needed Output:
Entry move A Normal.py
hello
Exit move A Normal.py

I can understand from the "Actual output" that the decorator is imported and each time a method is invoked it goes to "decorator.py" file and executes and so we get output shown in the "Actual output" .

Is there anyway that I could get the Needed Output but still at the same time I import the Decorator.py file ?

Was it helpful?

Solution

Changing your File_Name assignment to:

File_Name = inspect.getfile(f)

does what you want.
inspect.getfile() takes an object as its parameter, and f represents the wrapped function.

Source: http://docs.python.org/2/library/inspect.html#inspect.getfile

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top