Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to get the *full* name of the function I am in

Is there a way so that the following code:

import traceback

def log(message):
    print "%s: %s" %(traceback.extract_stack()[0:-1][-1][2], message)

def f1():
    log("hello")

class cls(object):
    def f1(self):
        log("hi there")

f1()
mycls = cls()
mycls.f1()

displays:

f1: hello
cls.f1: hi there

instead of:

f1: hello
f1: hi there

?

I tried to use module 'inspect' but was not successful...

Julien

EDIT:

The point here is for 'log' function to be able to retrieve its caller name on its own (using traceback, inspect, or any mean necessary).

I do not want to pass the class name, or anything else than 'message' to the 'log' function.

like image 761
Julien REINAULD Avatar asked Aug 02 '17 20:08

Julien REINAULD


People also ask

What does * mean in Python function?

Practical Data Science using Python The asterisk (star) operator is used in Python with more than one meaning attached to it. For numeric data types, * is used as multiplication operator >>> a=10;b=20 >>> a*b 200 >>> a=1.5; b=2.5; >>> a*b 3.75 >>> a=2+3j; b=3+2j >>> a*b 13j.

How do you get a function name inside a function in Python?

Method 1: Get Function Name in Python using function. func_name.

What is __ name __ in Python?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.


1 Answers

So I finally came up this method:

#!/usr/bin/env python3

def log(message):
    import inspect
    import gc
    code = inspect.currentframe().f_back.f_code
    func = [obj for  obj in  gc.get_referrers(code) if inspect.isfunction(obj)][0]
    print(func.__qualname__, message)

It needs python3 so that __qualname__ can be used.

like image 159
Julien REINAULD Avatar answered Dec 05 '22 10:12

Julien REINAULD