Get importer module from imported module

Duncan Booth duncan.booth at invalid.invalid
Mon Feb 7 06:08:33 EST 2005


dody suria wijaya wrote:

> 
> I found this problem when trying to split a module into two.
> Here's an example:
> 
>==============
> #Module a (a.py):
> from b import *
> class Main: pass
>==============
> 
>==============
> #Module b (b.py)
> def How():
>     Main_instance = module_a.Main()
>     return Main_instance
>==============
> 
>> import a
>> a.How()
> 
> 
> the problem would show at How() function. I have been unable
> to get variable pointing to module a from inside module b.
> In short, I need to have a variable pointing to the module
> whose importing me.
> 
> 

'import a' will let you reference module 'a', unless 'a' was invoked as a 
script in which case you would need 'import __main__'.

#Module b (b.py)
import a
def How():
    Main_instance = a.Main()
    return Main_instance

But: keep in mind that all statements (except 'global') are executable in 
Python, so you must not call How() until after the Main class has actually 
been created. This is one reason why it is generally safer to import a 
module and do the lookup when you need it instead of using 'from 
amodule import *' which can only get at the names which exist at the time 
it is executed.

A better solution  would be to structure your code so that your modules 
don't have any mutual dependencies. If your function 'How()' is in module b 
then just call 'b.How()' wherever you use it and lose the import of 'b' 
from 'a' altogether.



More information about the Python-list mailing list