global variables - how??

Sean Blakey sblakey at freei.com
Wed Apr 12 19:56:31 CEST 2000


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