Name of the caller function in Python
When Python executes the name of the function, it will jump to the start of the function definition and execute the code therein. The python script looks for the string ‘nameofthefunction’ and looks to see if it is found. If it is found then it will print the message and print the names of the variables in the global scope.
I wanted to have a quick look at how the name of a function determines where it is called. I found this post and thought it was pretty interesting. It showed some neat examples where different names could make a big difference to the performance of your functions, especially if you are writing tight loops.
We saw that in Python 3, functions with names like “myfunc” or “myfunc2” are generally called more than once per loop whereas named functions “sum” or “calcsum” are called only once per loop. This has an important effect on performance when the function is called very frequently (as it usually is in tight loops) as the overhead of a function call per loop is high.
So, how do we decide on function names? For starters, it’s important that you get the name right as it could have serious implications for the performance of your application. You’ll find that most of the functions used in real applications are pretty well named, but you can see there are exceptions.
The first thing I’d recommend is to read some of the code that you find on Github and see if there are any obvious naming patterns, such as:
def sum(a, b):
return a + b
which is an obviously named function as we can tell exactly what it does. But this is a bad example because it is also a builtin function and this is the case that the original post discusses.
def len(s):
return len(s)
def len(s):
return len(s)
def len(s):
return len(s)
There are lots of examples of this in the standard library and it’s easy to think that it doesn’t matter which one you use, but you may find that one of them is better than the others. It depends on the circumstances and the size of the project.
You may have a bunch of short functions, which may be hard to keep track of and it’s good to name them clearly and concisely.
import inspect
def first():
print("in first")
print("Called by", inspect.stack()[1][3])
second()
def second():
print("in second")
print("Called by", inspect.stack()[1][3])
def main():
first()
main()