profiler: can I find what calls my function?
<p>I'm working on a tool to visualize Python profile traces, and to do that, it would be useful to know what line a function is called from.</p>

<p>Suppose I have the following simple program:</p>

<pre><code>import time

def my_sleep(x):
  time.sleep(x)

def main():
  my_sleep(1)
  my_sleep(2)

main()
</code></pre>

<p>If I run cProfile on it (<code>python -m cProfile -o a.data a.py</code>), I get a marshaled file containing the following data structure:</p>

<pre><code> ('a.py', 3, 'my_sleep'): (2,
                           2,
                           1.4999999999999999e-05,
                           3.00576,
                           {('a.py', 6, 'main'): (2,
                                                  2,
                                                  1.4999999999999999e-05,
                                                  3.00576)}),
</code></pre>

<p>Essentially, this says that <code>my_sleep()</code> is called twice by <code>main()</code> on line 6, and this adds up to slightly over 3 seconds.</p>

<p>Is there any way to find out what line it's being called from, and not just what function? So in this case, <code>my_sleep()</code> is called on line 7 for 1 second, and line 8 for 2 seconds.</p>

<p>You may use <a href="https://docs.python.org/3/library/sys.html#sys._getframe" rel="nofollow"><code>sys._getframe(1)</code></a> in order to know the caller like so:</p>

<pre><code>import sys

def my_sleep():
    print("Line #" + str(sys._getframe(1).f_lineno))
    time.sleep(x)
</code></pre>

<p>Keep in mind doing things like that are usually not encouraged but if it's just temporary that's fine I guess.</p>

python performance profiling