Display Caller Of The Current Function In Python

python-logoIf you have spent enough time coding, then you know where I am going with this. As the code gets bigger, debugging gets trickier. Keeping track of everything becomes difficult, especially when you collaborate with others and your functions are being called by someone else’s functions. A lot of times, you may want see where your function is being called so that you can pinpoint where things went wrong. Luckily, Python has a neat way of doing it. You can get a list of all the locations where your function is being called, along with the line numbers.  

Let’s say you have two files named file1.py and file2.py. In file1.py, you are calling a function defined in file2.py named “add_numbers”. Now, file1.py looks like this:

from file2 import *
print add_numbers(3,4)

As you would expect, file2.py looks like this:

def add_numbers(a, b):
    return a+b

If you run file1.py, you will get “7” as the answer. Now if you want to display who called “add_numbers”, then modify file2.py as given below:

import sys
def add_numbers(a, b):
    print '{0.f_code.co_filename}:{0.f_lineno}'.format(sys._getframe(1))
    return a+b

You will get the following output when you run file1.py:

>> python file1.py

The above output indicates that the function was called in file1.py at line number 2. The number 7 in the next line indicates the sum of 3 and 4 given in file1.py.

This is just an example to demonstrate how to utilize this functionality in Python. You can place that line anywhere within a function and the location will be displayed every time that function is called.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s