Help on object scope?

bmaron2 at hotmail.com bmaron2 at hotmail.com
Sun Feb 25 16:51:15 EST 2007


On Feb 25, 9:37 am, hg <h... at nospam.org> wrote:
> bmar... 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

Dear hg,

Thank you for the advice, but that seems a bit unwieldy. My code will
have about 10 of these global objects, all of which interact with
eachother. It seems silly to have to pass 10 parameters around to each
instance I work with. I hope there is a smarter way to do it, or
perhaps someone can suggest a smarter way to code it.

Am I stuck with just having to put all the code in one file? That is
what I wanted to avoid, because the file will get incredibly long. It
seems like the only reason my code above failed is because there were
two separate modules. Perhaps I just need to import /lib/q.py in a
different way?

Many thanks.




More information about the Python-list mailing list