I've searched for it on the internet but so far I couldn't find an answer.
I have one library which is imported in every other file.
let's say the library is imported as import my_lib
in the files which uses it.
in mylib I'd like to do something like __imported_from__
so the code knows where the import is comming from. I need this for logging purposes (different call different logfile/logname)
This would be the log at the moment:
2018-09-13 01:36:00,921 - my_lib - INFO - Start Processing
2018-09-13 01:36:30,921 - my_lib - INFO - Done Processing
2018-09-13 01:37:00,921 - my_lib - INFO - Start Processing
2018-09-13 01:37:30,921 - my_lib - INFO - Done Processing
I want my_lib to contain the name from the imported file so it's possible to view where the call is comming from in my logging. Like the example below
2018-09-13 01:36:00,921 - import_from_file_1 - INFO - Start Processing
2018-09-13 01:36:30,921 - import_from_file_1 - INFO - Done Processing
2018-09-13 01:37:00,921 - import_from_file_2 - INFO - Start Processing
2018-09-13 01:37:30,921 - import_from_file_2 - INFO - Done Processing
Based on the answer I've wrote 2 lines which provide me with the data I want:
import inspect
from os.path import basename, splitext
imported_from_file = (inspect.stack()[1][1]) if __name__ != '__main__' else False
used_from = splitext(basename(imported_from_file))[0] if imported_from_file else __name__
In the file being imported, you can inspect the stack and get the first file name in the frames (after skipping the first frame, which is the current frame) that does not start with <
, which denotes an internal library:
import inspect
if __name__ != '__main__':
for frame in inspect.stack()[1:]:
if frame.filename[0] != '<':
print(frame.filename)
break
If you're using Python 2.7 you should instead use the second item of the frame tuple. In fact, in Python 2.7 the module doing the import is always in the second frame, so you can simply do:
import inspect
if __name__ != '__main__':
print(inspect.stack()[1][1])