how to know the importing file name from an imported file?

John Machin sjmachin at
Fri Apr 17 15:45:38 CEST 2009

On Apr 17, 9:17 pm, Visco Shaun <visc... at> wrote:
> Hi
> Is there a way to know the name of the script(say A), which is importing
> a module(say B), from B?
> ie in above situation i should be able to get name 'A' through some way
> in B, when A contains an 'import B' statement.

I find it difficult to imagine a sensible use case for a module
wanting to know which other module/script imported it. Functions/
methods should *not* contain "logic" like "I'm being imported by the
xyzzy script so I'll do something subtly different". Alternative
behaviours should be invoked explicitly through args in the APIs, not
through nasty manholes/trapdoors.

BTW "imported by" is not 100% identical to "called from".

Note: It's a frequent requirement to find the path to the originating
script, in the case that some resource files are located in the same
directory. Is that what you want? That path will be in sys.argv[0]


More information about the Python-list mailing list