How to get current function name inside this function in python

For my logging task, I want to register all the function names where my code goes

No matter who calls the function, I want the name of the function in which I declare this line

import inspect

def whoami():
    return inspect.stack()[1][3]

def foo():
    print(whoami())

he is currently printing foo, I want to printwhoami

+4
source share
3 answers

You probably want inspect.getframeinfo(frame).function:

import inspect

def whoami(): 
    frame = inspect.currentframe()
    return inspect.getframeinfo(frame).function

def foo():
    print(whoami())

foo()

prints

whoami
+13
source

For my logging task, I want to register all the function names where my code goes

Did you count decorators?

import functools
def logme(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        print(f.__name__)
        return f(*args, **kwargs)
    return wrapped


@logme
def myfunction();
    print("Doing some stuff")
+8
source

, , :

,

:

import logging               

def whoami():
    logging.info("Now I'm there")

def foo():
    logging.info("I'm here")
    whoami()
    logging.info("I'm back here again")

logging.basicConfig(
    format="%(asctime)-15s [%(levelname)s] %(funcName)s: %(message)s",
    level=logging.INFO)
foo()

2015-10-16 16:29:34,227 [INFO] foo: I'm here
2015-10-16 16:29:34,227 [INFO] whoami: Now I'm there
2015-10-16 16:29:34,227 [INFO] foo: I'm back here again
+6

Source: https://habr.com/ru/post/1611869/


All Articles