Julien REINAULD
Julien REINAULD

Reputation: 639

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.

Upvotes: 9

Views: 2372

Answers (2)

Julien REINAULD
Julien REINAULD

Reputation: 639

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.

Upvotes: 2

jmd_dk
jmd_dk

Reputation: 13090

The inspect module is very powerful, and can be used in a similar fashion to the way you use traceback to get the name of the function, and probably also the class name. But you can simply make use of the fact that you have the self instance variable, which knows of its own type/class:

import inspect

class cls(object):
    def f1(self):
        this_class_name = type(self).__name__
        this_func_name = inspect.currentframe().f_code.co_name
        print(this_class_name, this_func_name)

mycls = cls()
mycls.f1()

Upvotes: -1

Related Questions