Python Forum

Full Version: how can a function find the name by which it is called?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
how can a function find the name by which it is called?
You could try inspect.stack()[1][4][0] and see if that is useful.
import sys


def who_called_me():
    print(sys._getframe().f_back.f_code.co_name)


def i_am_the_caller():
    who_called_me()


i_am_the_caller()
Output:
i_am_the_caller
Depends on what is wanted, but that seems to display the name of the function, not the name that calls it. (similar to inspect.currentframe().f_code.co_name) If you assign the function to a variable and call the variable, it still returns the original function name.
if foo calls bar() the name i want is "bar", not "foo"

if foo does xyzzy = bar then calls xyzzy() the name i want is "xyzzy"
(Aug-14-2022, 07:05 PM)Skaperen Wrote: [ -> ]if foo does xyzzy = bar then calls xyzzy() the name i want is "xyzzy"
If foo does
xyz  = [bar, bar, bar]
what do you want when foo calls
xyz[0]()
? Also what is the purpose of all this?
(Aug-14-2022, 07:28 PM)Gribouillis Wrote: [ -> ]what do you want when foo calls
xyz[0]()
probably "xyz[0]". if i can get that piece of code, that would work. i suspect otherwise i'd get the function's def name.

(Aug-14-2022, 07:28 PM)Gribouillis Wrote: [ -> ]Also what is the purpose of all this?
to allow the function to output a more meaningful message in the case of certain errors.
(Aug-14-2022, 07:05 PM)Skaperen Wrote: [ -> ]if foo calls bar() the name i want is "bar", not "foo"

if foo does xyzzy = bar then calls xyzzy() the name i want is "xyzzy"

That's exactly what the 'inspect.stack()' line I posted above should do. Did you try it?
(Aug-14-2022, 10:57 PM)Skaperen Wrote: [ -> ]to allow the function to output a more meaningful message in the case of certain errors.
Then why don't you output the whole stack traceback, or simply raise an exception? The traceback is the most precise error report.
i am wanting to phrase the message in a certain context for this user base that is following some specific instructions to get specific results. these users are running commands (in the future, to use a GUI app) that constructs some Python code. these users are not coders and probably have no understanding of a traceback or the Python message. if the function can get the name that would simplify the task. otherwise i will need to add another argument in both the function and all makers of calling code.
Pages: 1 2