Help on object scope?
Hendrik van Rooyen
mail at microcorp.co.za
Mon Feb 26 00:54:12 EST 2007
"hg" <hg at nospam.org> wrote:
> 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
Make a third file for all the system wide globals, say param.py:
global r
r = 42
> >
> > My file p.py looks like this:
> >
> > ---
> >
> > from lib import q
> >
> > def main():
from param import *
> > global r
> > r = q.object1()
> > s = q.object2()
> >
> > if __name__ == "__main__":
> > main()
> >
> > ---
> >
> > My file q.py in the subdirectory lib looks like this:
from param import *
> >
> > 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.
Correct.
>
> I suggest you find another way such as passing your object as a parameter
or make the third file and import it everywhere you need them...
- Hendrik
More information about the Python-list
mailing list