from pack.mod import f
How to get from object f information about import – 'pack.mod'
I can get it using f.__module__
but if function def in module where i get this attribute (f.__module__) it return '__main__'. But i need real path here – 'pack.mod'
I found this way to get this information:
inspect.getmodule(f).__file__
then i can sub start path from sys.path, replace / on . and get path like – 'pack.mod'
But may be exist some more convenient way?
What
inspect.getmodule(f)does internally, per inspect.py’s sources, is essentiallysys.modules.get(object.__module__)— I wouldn’t call using that code directly “more convenient”, though (beyond the “essentially” part,inspecthas a lot of useful catching and correction of corner cases).Why not call directly inspect.getsourcefile(f)?
Edit: reading between the lines it seems the OP is trying to do something like
and within
bla.py(which is thus being run as__main__) determine “whatfromorimportstatement could a different main script use to import this function from within me?”.Problem is, the question is ill-posed, because there might not be any such path usable for the purpose (nothing guarantees the current main script’s path is on
sys.pathwhen that different main script gets run later), there might be several different ones (e.g. both/foo/barand/foo/bar/bazmight be onsys.pathand/foo/bar/baz/__init__.pyexist, in which casefrom baz.bla import fandfrom bla import fmight both work), and nothing guarantees that some other, previoussys.pathitem might not “preempt” the import attempt (e.g., say/foo/bar/bazis onsys.path, but before it there’s also/fee/fie/foo, and a completely unrelated file/fee/fie/foo/bla.pyalso exists — etc, etc).Whatever the purpose of this kind of discovery attempt, I suggest finding an alternative architecture — e.g., one where
from baz.bla import fis actually executed (as the OP says at the start of the question), so thatf.__module__is correctly set tobaz.bla.