Question about scope

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 23 18:17:36 EDT 2008


On Thu, 23 Oct 2008 21:08:12 -0400, Pat wrote:

> Stripping out the extra variables and definitions, this is all that
> there is.
> Whether or not this technique is *correct* programming is irrelevant.

Oh rly?

Well, sure, you can write bad code if you like, and make your actual job 
much harder. No skin off our nose, except when you come along asking for 
free debugging out of the goodness of our hearts.


> I simply want to know why scoping doesn't work like I thought it would.
> 
> 
> ---> myGlobals.py file:
> 
> class myGlobals():
>      remote_device_enabled = bool

Creates a class myGlobals with a class attribute called 
"remote_device_enabled" which is equal to the class bool.

Why not just initialise it to True here?

Why is it a class attribute instead of an instance attribute?

 
> ---> my initialize.py file:
> 
> from myGlobals import *

Creates a name called "myGlobals" which is local to this module. It is 
bound to the same myGlobals class as defined by myGlobals.py module.


> def initialize():
>      myGlobals.remote_device_enabled = True

Sets the class attribute remote_device_enabled to a useful value at last.

 
> ---> my main.py file:
> 
> import from myGlobals import *

Gives a Syntax error.

If you're not going to be bothered to test the code before you send it, 
I'm not sure I can be bothered to debug it for you.


> RDE =  myGlobals.remote_device_enabled

Creates a local name RDE which takes its initial value from the class 
attribute remote_device_enabled. This could be more easily written as:

RDE = bool

since initialize() hasn't been called yet.


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

Obvious something else is happening in your real code, because following 
the program logic you've shown (ignoring the SyntaxError), it should give 
the correct value: RDE is bool. By a lucky accident, "if bool" evaluates 
as True and process_device() will be called.

I suggest that your spaghetti code is far more complicated and you 
haven't successfully teased out a minimal thread that demonstrates the 
problem.


-- 
Steven



More information about the Python-list mailing list