Python Forum

Full Version: Can a module tell where it is being imported from?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:
    ...
you can run from command line: python -m site or python3 -m site)

or run site.getsitepackages(): python -c 'import site; print(site.getsitepackages())
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.
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")