Global var access in imported modules?

RgeeK slfdsasdssaf at spam.not
Wed Aug 27 21:51:52 EDT 2008


Dennis Lee Bieber wrote:
> On Wed, 27 Aug 2008 16:21:03 -0400, RgeeK <Ross at no.thanks.spammers>
> declaimed the following in comp.lang.python:
> 
>> I have a main module doStuff.py and another module utility.py.  At the 
>> start of doStuff.py I call
>>
>>     import utility.py
> 
> 	I hope not...	import utility	no .py
>> Then I also proceed to initiallize some global variables
>>
> 	Python does not have global variables. Names belong within a module
> (or within functions defined within the module).
> 
>> sName = ""
>>
>> Then I create a class, some methods etc.  In one of the methods I assign
>> a value to my variable sName.  Then I call a function from within
>> my utility.py file:
>>
>>   utility.makeOne(stuff)
>>
>>
>> Within my utility.py file, I define the makeOne function. But I want to 
>> use that same global variable "sName"  In utility.py I have tried to 
>> indicate that I'm using the global "sName" through the statement:
>>
>>    global sName
>>
> 	The global statement is only used within functions (def blocks) to
> indicate that "writes" to the specified name are to modify the MODULE
> level version of the name, otherwise a write modifies a function local
> version of the name (you don't need global for read-only access of
> names, the search for names first looks inside the function, then out to
> the module)
>  
>> But when I go to use the variable it still gives me an error:
>>
>>    NameError: global name 'sName' is not defined
>>
>> I thought perhaps I need to indicate 'globality' in my main module, so 
>> before I initiallized sName in doStuff.py I added:
>>
>> global sName
>>
>> But it doesn't help me.   I had this issue before and resolved it by 
>> declaring the variable global in the sub-module utility.py, but then I 
>> needed to reference it in my main module with a prefix:
>>
>>   utility.sName = ""
>>
>> It's more verbose,and defining globals in a submodule seems backward.
>> But also, what if I need to access "sName" in another imported module, 
>> say "otherstuff.py"?   I would do my "import otherstuff" call in my main 
>> module, but would I have to put an "import utility" into the 
>> otherstuff.py file?
>>
> 	If you really need "globals" the common solution is to create a
> module such as "myglobals", define all the shared names within that
> module, and import that module where ever you need access to one of the
> names. And yes, you will need to qualify all those names with the module
> name (though you can do things like:
> 
> import myglobals as mg
> 
> and then use
> 
> mg.somename
> 
> instead of
> 
> myglobals.somename)
>  


Thanks for the reply.  Good to see that approach has broad support :) 
I'll do that.  I like the idea of a nice short alias for the import to 
keep the qualifications brief.

Ross.



More information about the Python-list mailing list