Variable passing between modules.

Jeff Shannon jeff at ccvcorp.com
Wed Sep 8 17:37:29 EDT 2004


Golawala, Moiz M (GE Infrastructure) wrote:

>Hi All, 
>
>I want to pass a value between 2 modules. Both the modules are scripts (no classes involved). Does anyone know how I can do that. For eg:
>
>in module1 
>
>
>if __name__ == '__main__':
>	someVar = 'hello'
>	import module2
>
>
>in module 2
>
># here I would like to use someVar
>print someVar
>
>  
>


The best way to do this is to put your module2 code inside a function, 
and simply call that function with someVar as an argument. 

--- module2.py -----

def go(somevar):
    print somevar

--- module1.py -----
import module2
somevar = "hello"
module2.go(somevar)

It *is* possible to insert a variable into another module's namespace, 
like so:

import module2
module2.somevar = somevar

However, this won't accomplish what you want, because all of the code in 
module2 is executed when you import module2.  If that code is all def 
statements, then you've created a bunch of functions that can be used 
later; however, if that code is all module-level imperative code, as you 
seem to be showing in your example, then it's all been executed by the 
time that module1 returns from the import statement.  Inserting a 
variable into module2's namespace *will* let you use that variable as a 
global in any function in module2, but this has all of the drawbacks 
that globals always have plus a few more (tight coupling with module1, 
the potential to mistakenly think that rebinding module2.somevar will 
also rebind module1.somevar, etc)...

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list