Well it's an interesting question, can a function know what name it's called by? As far as I know, this piece of information is not stored in the stack or anywhere else, so to fetch it, we'll have to go into higher dimensions, or go meta, to manipulate the info of the source itself.
The result may not be useful, but it's funny :)
Below is the clumsy code:
import inspect
import io
import re
def get_my_name(func_obj):
caller_frame = inspect.currentframe().f_back.f_back
caller_mod = inspect.getmodule(caller_frame)
mod_src = inspect.getsource(caller_mod)
call_lineno = caller_frame.f_lineno
stream = io.StringIO(mod_src)
for i in range(0, call_lineno):
line = stream.readline()
m = re.findall('[_a-zA-Z0-9]+(?=\()', line)
m = [fname for fname in m if caller_frame.f_locals[fname] == func_obj]
return m
def some_func(n):
print(get_my_name(some_func))
return n*n
def caller():
f = some_func
return f(2)
caller()
baris just a reference tofoo.'bar'? You have to write name anyway.