Variable passing between modules.

  • Thread starter Golawala, Moiz M (GE Infrastructure)
  • Start date
G

Golawala, Moiz M (GE Infrastructure)

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


Thanks,
Moiz Golawala
GE Infrastructure, Security
Software Engineer
Enterprise Solutions

T 561 994 5972
F 561 994 6572
E (e-mail address removed)
www.gesecurity.com

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

Jeff Shannon

Golawala said:
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
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top