0

I'm creating a custom log function which needs to get the name of the method running it. How can I get the method's name passed to the log function. For example, this:

def log(msg):
    print(f'{runningMethod}: {msg}') # runningMethod is the intended parameter to get passed
    return


def testFunc():
    log("Running")
    return

testFunc()

should output this:

testFunc: Running

It is required that log() only takes that one argument

esantix
  • 323
  • 5
  • 26

1 Answers1

2

Use inspect.currentframe() and take the previous:

eg:

import inspect

def log(msg):
    caller = inspect.currentframe().f_back
    runningMethod = caller.f_code.co_name
    print(f'{runningMethod}: {msg}') # runningMethod is the intended parameter to get passed
    return


def testFunc():
    log("Running")
    return

testFunc()
Jon Clements
  • 138,671
  • 33
  • 247
  • 280