Help on object scope?

hg hg at nospam.org
Sun Feb 25 09:37:28 EST 2007


bmaron2 at hotmail.com wrote:

> Hello everybody,
> 
> I have a (hopefully) simple question about scoping in python. I have a
> program written as a package, with two files of interest. The two
> files are /p.py and /lib/q.py
> 
> My file p.py looks like this:
> 
> ---
> 
> from lib import q
> 
> def main():
>   global r
>   r = q.object1()
>   s = q.object2()
> 
> if __name__ == "__main__":
>   main()
> 
> ---
> 
> My file q.py in the subdirectory lib looks like this:
> 
> class object1:
>   t = 3
> 
> class object2:
>   print r.t
> 
> ---
> 
> Python gives me an error, saying it can't recognize global name r.
> However I define r as global in the top-level main definition! Can
> anyone suggest how I can get around this, if I want to define and bind
> global names inside of main() which are valid in all sub-modules?
> 
> Thanks very much for your help!

Might be wrong, but globals can only be global to the module they're
declared in.

I suggest you find another way such as passing your object as a parameter

hg





More information about the Python-list mailing list