0

In Python, is there a way to determine which module/package imported a downstream package? For example, imagine if we have package_A, package_B, and package_C. In my scenario, both package_A and package_B depend on package_C. So, if I import package_A, package_C automatically gets imported. Similarly, if I import package_B, package_C automatically gets imported.

Assuming that I can change/modify package_C, is there a way to determine whether package_C was imported by package_A or package_B or neither? In other words, I want to add code to package_C that will detect whether the parent importer included package_A, package_B, or neither. Note that package_A may not be directly importing package_C (i.e., package_A might import package_Q, which imports package_C).

I've tried looking at traceback but I'm not able to make any progress.

slaw
  • 6,591
  • 16
  • 56
  • 109
  • 1
    Does this answer your question? [How can I check if a module has been imported?](https://stackoverflow.com/questions/30483246/how-can-i-check-if-a-module-has-been-imported) – Christopher Peisert Apr 08 '22 at 13:41
  • Thanks @ChristopherPeisert. I think this is closer but it doesn't tell me that `package_A` imports `package_Q`, which then imports `package_C`. It's possible that somebody imports `package_A.other_module`, which does not import `package_C` downstream and maybe `package_C` is imported in, say, `__main__`. So, I'm looking for some sort of lineage or "importing stack" if such a thing exists – slaw Apr 08 '22 at 13:48

0 Answers0