global variables - how??

Anders Eggers-Krag aek at mail1.stofanet.dk
Wed Apr 12 15:47:19 EDT 2000


it is obvious not to use global variables except when the use of them is
obvious,
in my case I could otherwise send them along with every function, creating a
huge
overhead passing a million pointers around, using exactly the same amount of
memory,
or in fact more, than I would using globals.

I did figure out how to do it myself after a lot of trying, but as you said
it is ugly,
but this really anoys me, and I *was* starting to like python...


--
Anders Eggers - Krag


"Sean Blakey" <sblakey at freei.com> wrote in message
news:20000412175218.784841CE49 at dinsdale.python.org...
> On 12 Apr, William Park wrote:
> > On Wed, Apr 12, 2000 at 07:28:37PM +0200, Anders Eggers-Krag wrote:
> >> how do I define a propper global variable that works in all functions
in all
> >> modules?
> >
> > As far as I know, you can't.  You have to use 'global ...' inside all
> > your functions.
> >
> > --William
> >
> >>
> >> I have tried simply
> >> defining one outside of any function in the main module,
> >> I have tried using the global keyword under the same cicumstances,
> >> but they are not even avialible inside of functions within the main
> >> module...
> >>
> >>
> >> --
> >> Anders Eggers - Krag
> >>
> >>
> >> --
> >> http://www.python.org/mailman/listinfo/python-list
> >
>
> Short answer: Python discourages globals.  This is probably intentional.
>
> Long answer:  You can do some work with globals, but it is painful and
> ugly.  You also need to keep track of namespaces (globals from your
> main module will be in the __main__ namespace).
>
> For example:
> -----file one.py-----
> TEST_VALUE = 'spam'
>
> def printTest():
>     print TEST_VALUE
>
> def changeTest():
>     global TEST_VALUE # Without this, the next line
>     # will simply assign 'spamspam'
>     # to the local variable
>     # TEST_VALUE
>     TEST_VALUE = TEST_VALUE + TEST_VALUE
>
> if __name__ == '__main__':
>     import two
>     printTest()
>     two.printTest()
>     changeTest()
>     printTest()
>     two.printTest()
>
> -----file two.py-----
> import __main__
>
> def printTest():
>     print __main__.TEST_VALUE
>
>
> Now, from the shell:
> seanb at seanb:~$ python one.py
> spam
> spam
> spamspam
> spamspam
>
>
> --
>
> Sean Blakey
> FreeInternet.com
> sblakey at freei.com
> (253)796-6500x1025
>
>





More information about the Python-list mailing list