Plane Wryter
Plane Wryter

Reputation: 1379

In Python v3.7.x, How Can a Called Function Obtain the Name of the Calling Function?

Pythonistas,

In Python v3.7.x, or later, how can a called function obtain the name of the calling function...WITHOUT programming the calling function's name as an argument?

In the code example below, how can NAME_OF_CALLING_FUNCTION be populated with...well...the name of the calling function? (Say...something to do with the Standard Library? Dunders/Magic Names?)

Example code:

logging.basicConfig(filename='my_log_file.log',
    level = logging.DEBUG,
    format = A_VALID_FORMAT_STRING)

def logging_function(log_message):
    #Simplified for StackOverflow
    msg = str(NAME_OF_CALLING_FUNCTION) + ' DEBUG: Something...'
    logging.debug(msg)

def caller_one():
    #Simplified for StackOverflow
    logging_function(DIAGNOSTIC_MESSAGE_ONE)
    return(0)

def caller_two():
    #Simplified for StackOverflow
    logging_function(DIAGNOSTIC_MESSAGE_TWO)
    return(0)

def main():
    #Simplified for StackOverflow
    caller_one()
    caller_two()

Ideally, when caller_one() and caller_two() execute, my_log_file.log will contain something like this:

DATE/TIME Calling function: caller_one DEBUG: Something...
DATE/TIME Calling function: caller_two DEBUG: Something...

Many thanks in advance for any assistance you can provide!

With gratitude, Plane Wryter

Upvotes: 1

Views: 60

Answers (1)

ted
ted

Reputation: 14764

Use the inspect module. From this source:

import inspect
# functions
def whoami():
    return inspect.stack()[1][3]
def whosdaddy():
    return inspect.stack()[2][3]
def foo():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
    bar()
def bar():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
johny = bar
# call them!
foo()
bar()
johny()
hello, I'm foo, daddy is ?
hello, I'm bar, daddy is foo
hello, I'm bar, daddy is ?
hello, I'm bar, daddy is ?

in your case:

msg = str(inspect.stack()[1].function) + ' DEBUG: Something...'

Example:

import inspect

def logging_function(log_message):
    #Simplified for StackOverflow
    msg = str(inspect.stack()[1].function) + ' DEBUG: Something...'
    print(msg)

def f1():
    logging_function("")

def f2():
    logging_function("")

f1()
f2()
f1 DEBUG: Something...
f2 DEBUG: Something...

Upvotes: 2

Related Questions