Question about scope

Pat Pat at junk.net
Fri Oct 24 03:08:12 CEST 2008


Bruno Desthuilliers wrote:
> Pat a écrit :
>> I have a Globals class.
> 
> Not sure it's such a great idea, but anyway... What's the use case for 
> this class ? There are perhaps better (or at least more idiomatic) 
> solutions...
> 
>> In it, I have a variable defined something like this:
>>
>> remote_device_enabled = bool
> 
> Could you show actual code ? It would really help. But it seems your 
> 'Globals' class is mostly 1/ a singleton and 2/ used for application 
> wide settings. Is that right ?
> 
>> In one module, I assign True/False to Globals.remote_device_enabled. 
> 
> Directly to the class ?
> 
> Please, once again, provide real code. Well... not necessarily your 
> whole code, but at least minimal working code that reproduces the problem.
> 
>> Once set, this value never changes.
>>
>> In another module, at the top after the imports statements, I tried this:
>>
>> from Globals import *
> 
> <ot>
> The convention is to use lower case names for modules (and MixedCase 
> names for classes). This avoids confusion between synonym classes and 
> modules...
> </ot>
> 
>> RDE = Globals.remote_device_enabled
>>
>> This way, I thought that I could just use 'if RDE:'
>>
>> Within the functions, however, I get a different value.  What am I 
>> misunderstanding?
> 
> Not enough informations, and my crystal ball is out for repair. Sorry. 
> Perhaps some actual code may help ?-)
> 
>> I tried this at the top of the module (but it didn't word):
>>
>> global RDE
> 
> Outside a function body, the 'global' statement is a no-op. In Python, 
> 'global' really means 'module-level', so anything defined at the module 
> level is already as global as it can be.
> 
>> RDE =  Globals.remote_device_enabled
>>
>> Of course, within a function, the variable using the same two lines of 
>> code assigns the correct value to RDE.
> 
> Sorry Pat, but there's just not enough context for us to guess what's 
> wrong. It's easy enough to get it wrong with real code, so trying to 
> guess is just a waste of time.


Stripping out the extra variables and definitions, this is all that 
there is.
Whether or not this technique is *correct* programming is irrelevant. I 
simply want to know why scoping doesn't work like I thought it would.


---> myGlobals.py file:

class myGlobals():
     remote_device_enabled = bool

---> my initialize.py file:

from myGlobals import *
def initialize():
     myGlobals.remote_device_enabled = True

---> my main.py file:

import from myGlobals import *
RDE =  myGlobals.remote_device_enabled

def main():
     if RDE:    # this will not give me the correct value
         process_device()








More information about the Python-list mailing list