-1

Are there any ways to obtain a path of a file corresponding to a function object which is passed to a decorator function?

Finally I need a directory of the file.

def mydec(arg):
    def dec_inner(func):
        def wrapper(*args, **kwargs):
            # how to detect a path where func is defined?
        return wrapper
     return dec_inner
sergzach
  • 6,578
  • 7
  • 46
  • 84

1 Answers1

3

You can find the name of the module a function comes from using the __module__ attribute:

>>> from random import choice
>>> choice.__module__
'random'

You can get the module from its name via the sys.modules dictionary:

>>> sys.modules['random']
<module 'random' from 'C:\Python27\lib\random.pyc'>

And the file path itself from the module attribute __file__. Putting all of that together:

>>> sys.modules[choice.__module__].__file__
'C:\\Python27\\lib\\random.pyc'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437