Variable passing between modules.

Jeff Shannon jeff at ccvcorp.com
Thu Sep 9 15:35:39 EDT 2004


Josef Meile wrote:

> Golawala, Moiz M (GE Infrastructure) wrote:
>
>> 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.
>
>
> You could do this:
>
> module1:
>
> varDict={}
> varDict['foo1']='hello'
> varDict['foo2']='world'
>
> module2:
>
> from module1 import varDict
>
> print varDict.get('foo1')
> print varDict.get('foo2')


But if you need to import module2 in module1, you'll have problems with 
circular imports.  (Using 'from module import name' doesn't prevent 
Python from needing to process the entire module; it just means that 
only 'name', and not 'module', is added to your namespace.)

If you really need a big set of global variables (a practice which, in 
general, I'd recommend avoiding), then at very least you should create a 
globals.py module which contains nothing but these  variables.  Other 
modules can then 'import globals; print globals.myvar' or whatever.  
This is, at least, cleaner than C globals, since it can also be viewed 
as establishing a configuration object which passively maintains 
application state (and which just happens to be an instance of ModuleType).

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list