Python Forum
Can a module tell where it is being imported from?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can a module tell where it is being imported from?
#1
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:
    ...
Reply
#2
you can run from command line: python -m site or python3 -m site)

or run site.getsitepackages(): python -c 'import site; print(site.getsitepackages())
Reply
#3
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.
stevendaprano likes this post
Reply
#4
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")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  can not import anaconda pandas module. PySpark pandas module is imported!! aupres 0 715 Aug-06-2023, 01:09 AM
Last Post: aupres
  module detecting if imported vs not Skaperen 1 1,669 Nov-19-2021, 07:43 AM
Last Post: Yoriz
  Error when refering to class defined in 'main' in an imported module HeRo 2 2,376 Apr-13-2021, 07:22 PM
Last Post: HeRo
  [newbie] Why is a module imported twice? Winfried 3 4,075 Apr-02-2021, 04:48 AM
Last Post: deanhystad
  how to do setattr() from an imported module nutron 3 3,342 Sep-20-2019, 08:16 PM
Last Post: nutron
  argparse and imported modules spatialdawn 2 5,439 Dec-01-2018, 12:35 PM
Last Post: spatialdawn
  passing a value to imported code Skaperen 0 1,983 Sep-28-2018, 03:59 AM
Last Post: Skaperen
  function NOT imported from a module Skaperen 10 6,041 Aug-31-2018, 07:30 AM
Last Post: Gribouillis
  decorate an imported function? Skaperen 3 9,923 May-22-2017, 08:05 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020