Variable passing between modules.

Golawala, Moiz M (GE Infrastructure) Moiz.Golawala at ge.com
Thu Sep 9 15:11:13 CEST 2004


The example that I provided was very simplistic. I have a tones of methods in module 2 and the method need to get executed and need the someVar value. 

I was thinking like setting up some a value in some global VM list which can be accessed by all modules.

Moiz Golawala
GE Infrastructure, Security
Software Engineer
Enterprise Solutions

T 561 994 5972
F 561 994 6572
E moiz.golawala at ge.com 
www.gesecurity.com

791 Park of Commerce Blvd., Suite 100
Boca Raton, FL, 33487, U.S.A.
GE Security, Inc.


-----Original Message-----
From: python-list-bounces+moiz.golawala=ge.com at python.org
[mailto:python-list-bounces+moiz.golawala=ge.com at python.org]On Behalf Of
Jeff Shannon
Sent: Wednesday, September 08, 2004 5:37 PM
To: python-list at python.org
Subject: Re: Variable passing between modules.


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

-- 
http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list