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

Discussion in 'Python' started by Visco Shaun, Apr 17, 2009.

  1. Visco Shaun

    Visco Shaun Guest

    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.
    --
    Thanks & Regards
    visco
    Visco Shaun, Apr 17, 2009
    #1
    1. Advertising

  2. Visco Shaun

    Peter Otten Guest

    Visco Shaun wrote:

    > 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?
    Peter Otten, Apr 17, 2009
    #2
    1. Advertising

  3. Visco Shaun

    John Machin Guest

    On Apr 17, 9:17 pm, Visco Shaun <> 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]

    Cheers,
    John
    John Machin, Apr 17, 2009
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. plb
    Replies:
    2
    Views:
    345
  2. R. David Murray
    Replies:
    0
    Views:
    249
    R. David Murray
    Apr 17, 2009
  3. Dun Peal
    Replies:
    10
    Views:
    456
    Chris Rebert
    May 3, 2011
  4. Andries

    I know, I know, I don't know

    Andries, Apr 23, 2004, in forum: Perl Misc
    Replies:
    3
    Views:
    228
    Gregory Toomey
    Apr 23, 2004
  5. Volker Nicolai
    Replies:
    9
    Views:
    937
    Fabian Pilkowski
    Jul 4, 2005
Loading...

Share This Page