Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the file name of the function that is passed to my decorator in python?

I want to get the original file/scriptname, etc of the function that is being decorated. How can I do that?

   def decorate(fn):
        def wrapped():
            return "scriptname: " + fn.scriptname?  
        return wrapped

I tried using fn.__code__ but that gave me more stuff that I needed. I could parse that string to get the function name, but was wondering if there is a more elegant way to do it

like image 543
theRealWorld Avatar asked Aug 28 '12 04:08

theRealWorld


People also ask

How do I read a Python decorator?

A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

What is the return type of the decorator?

Decorators accept a function and return a function This function accept a number and returns either True or False depending on whether that number is prime or not.

How do I print a decorator in Python?

You can create a decorator that can print the details of any function you want. To do this the functions in Python certain attributes. One such attribute is __code__ that returns the called function bytecode. The __code__ attributes also have certain attributes that will help us in performing our tasks.

What is the correct syntax for using a decorator?

Decorators use a special syntax in JavaScript, whereby they are prefixed with an @ symbol and placed immediately before the code being decorated.


2 Answers

import inspect
inspect.getfile(fn)

This won't work for builtin functions though, you have to fall back to inspect.getmodule for those.

like image 163
John La Rooy Avatar answered Oct 05 '22 02:10

John La Rooy


Try this:

return "filename: " + fn.func_code.co_filename
like image 20
MostafaR Avatar answered Oct 05 '22 01:10

MostafaR