Is there a version of __file__ that when used in a function, will get the name of the file that uses the library?
<p>So, as a joke I wrote a version of goto for python that I wanted to use as a library. The function I wrote for it is as follows.</p>

<pre><code>def goto(loc):
  exec(open(__file__).read().split("# "+str(loc))[1],globals())
  quit()
</code></pre>

<p>This works for cases where it is in the file where goto is used, such as this:</p>

<pre><code>def goto(loc):
  exec(open(__file__).read().split("# "+str(loc))[1],globals())
  quit()


# hi
print("test")
goto("hi")
</code></pre>

<p>However, if I import goto in another file, it doesn't work as</p>

<pre><code>__file__
</code></pre>

<p>will always return the file with the function in it, not the one it is used in. Is there an equivalent of file that will allow me to import a file with the goto function in it and have it work?</p>

<p>Yes, you can if you inspect the call stack:</p>

<pre><code>import inspect

def goto():
    try:
        frame = inspect.currentframe()
        print(frame.f_back.f_globals['__file__'])
    finally:
        # break reference cycles
        # https://docs.python.org/3.6/library/inspect.html#the-interpreter-stack
        del frame

goto()
</code></pre>

<p>Note that the call stack is actually python implementation dependent -- So for some python interpreters, this might not actually work...</p>

<p>Of course, I've also shown you how to get the caller's globals (<code>locals</code> can be found via <code>frame.f_back.f_locals</code> for all of your <code>exec</code>ing needs).</p>

<p>Also note that <a href="https://docs.python.org/3.6/reference/datamodel.html#frame-objects" rel="nofollow">it looks like you can implement a jump command</a> by writing to the frame's <code>f_lineno</code> -- which might be a better way to implement your <code>goto</code>.  I've never done this though so I can't really advise you on how to actually code it up :-)</p>

python python-3.x goto