tags:

views:

88

answers:

4

How do I find the name of the file that is the "importer", within the imported file?

If a.py and b.py both import c.py, is there anyway that c.py can know the name of the file importing it?

A: 

In the top-level of c.py (i.e. outside of any function or class), you should be able to get the information you need by running

import traceback

and then examining the result of traceback.extract_stack(). At the time that top-level code is run, the importer of the module (and its importer, etc. recursively) are all on the callstack.

Phil
Thanks Phil, this came the closest to what I needed. I would mark it helpful, but I lack the required rep points. :)
Walking Wiki
+1  A: 

It can be done by inspecting the stack:

#inside c.py:
import inspect
FRAME_FILENAME = 1
print "Imported from: ", inspect.getouterframes(inspect.currentframe())[-1][FRAME_FILENAME]
#or:
print "Imported from: ", inspect.stack()[-1][FRAME_FILENAME]

But inspecting the stack can be buggy. Why do you need to know where a file is being imported from? Why not have the file that does the importing (a.py and b.py) pass in a name into c.py? (assuming you have control of a.py and b.py)

lost-theory
Not just "can be buggy", but "won't work as expected", as the module will be evaluated only once, even if imported multiple times.
Charles Duffy
+2  A: 

That's why you have parameters.

It's not the job of c.py to determine who imported it.

It's the job of a.py or b.py to pass the variable __name__ to the functions or classes in c.py.

S.Lott
You present a good argument and technique, but my code requires an action (a method override) immediately after the imports are executed. For simplicity's sake I wanted to have the reference automatically found instead of calling a class with a __name__ parameter after the import line.
Walking Wiki
+1  A: 

Use

sys.path[0]

returns the path of the script that launched the python interpreter. If you can this script directly, it will return the path of the script. If the script however, was imported from another script, it will return the path of that script.

See Python Path Issues

Dave