Python Forum
Can a module tell where it is being imported from? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Can a module tell where it is being imported from? (/thread-36915.html)



Can a module tell where it is being imported from? - stevendaprano - Apr-11-2022

Say I have a module, "sneaky.py". The first time sneaky is imported, the body of the module runs. (On subsequent imports, sneaky is just loaded from the module cache.)

Is there something sneaky can do to identify the module that imported it that first time? (On subsequent imports, obviously not.)

# sneaky.py
if module_importing_me is spam:
    ...



RE: Can a module tell where it is being imported from? - Larz60+ - Apr-11-2022

you can run from command line: python -m site or python3 -m site)

or run site.getsitepackages(): python -c 'import site; print(site.getsitepackages())


RE: Can a module tell where it is being imported from? - deanhystad - Apr-11-2022

I think stevendaprano wants the imported package (sneaky.py) to get the module that imported it.

If you raise an exception in your module the traceback includes the calling module, so it is most surely possible. Something like this?
import sys
print("Importing sneaky.py")
for i in range(1, 100):
    caller = sys._getframe(i).f_code.co_filename
    if not "bootstrap" in caller:
        print(caller)
        break
There has to be something better. But at least it is a starting place.


RE: Can a module tell where it is being imported from? - stevendaprano - Apr-12-2022

Thanks deanhystad that's exactly it, I want my module sneaky to identify the module which directly called import sneaky.

Thanks to your hint, this works for me:

import sys
print("importing sneaky")
i = 1  # skip this frame
while True:
    try:
        name = sys._getframe(i).f_code.co_filename
    except ValueError:
        break
    if not name.startswith('<frozen importlib.'):
        print("importer was", name)
        break
    else:
        i += 1
else:  # No break from while.
    print("importer could not be found")