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

V

Visco Shaun

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.
 
P

Peter Otten

Visco said:
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.

While

import sys
print "I'm imported by %r" % sys._getframe(1).f_globals["__name__"]

will sometimes work this is a bad idea. What are you trying to achieve?
 
J

John Machin

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]

Cheers,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top