Yes, there is a way to do this, although the right decision will be difficult. You can use the inspect module to access the call stack. This allows you to see what the code called the function looks like.
The stack looks something like this:
[(<frame object at 0x107de1d38>, 'path/to/function/file.py', 6, 'func', ['\tstack = inspect.stack()\n'], 0), (<frame object at 0x107d34050>, 'path/to/calling/file.py', 17, '<module>', ['func()\n'], 0)]
Note the second and final entry: ['func()\n'] . This shows the code that calls your function. Although the function name is displayed elsewhere on the stack, it always shows the actual function name, regardless of how it is called. Therefore, you need to do a little work yourself to determine if the call was made directly or using an assigned variable.
This is the only way to get the function name. Python does not have a function to extract the function name from the function itself.
To make it clear that this will be more complicated than just if func_name in stack , I covered the function a bit to show a couple of real-life examples of how the function can be called and how it will look, Since the function cannot determine its own name, it is hard-coded at the top of the function.
import inspect def func(var=None, default=''): my_name = 'func' stack = inspect.stack() func_call = stack[-1][4][0] print func_call.rstrip() # `func_call` contains a trailing newline # logic to determine if the name matches # ... # ... x = func func() return_value = x(var=1) print func() if x(): pass
Fingerprints:
func() return_value = x(var=1) print func() None