The global statement

Bengt Richter bokr at oz.net
Wed Jul 23 18:02:44 CEST 2003


On Wed, 23 Jul 2003 16:56:08 +0200, Thomas =?ISO-8859-15?Q?G=FCttler?= <guettler at thomas-guettler.de> wrote:

>David Hitillambeau wrote:
>
>> Hi guys,
>> As I am new to Python, i was wondering how to declare and use global
>> variables. Suppose i have the following structure in the same module (same
>> file):
>> 
>> def foo:
>>   <instructions>
>>   <instructions>
>> def bar:
>>   <instructions>
>>   <instructions>
>> 
>> I want to enable some sharing between the two functions (foo and bar)
>> using one global variable in such a way that each function can have read
>> and write access over it.
>
>Hi David,
>
>global BAD
Don't need the above line if you are already in global scope.
>BAD=1
>
>def foo():
>    global BAD
>    print BAD
>
>def bar():
>    global BAD
>    print BAD
>
>foo()
>bar()
>
>If foo and bar are in the same file, 
>you don't need the "global".
>
Unless you want to rebind it. Then you need it in order not
to get the default behaviour of creating a local within the function.
E.g., here are some variations to think about. Note what gets changed and when:

 >>> BAD = 'global BAD'
 >>> def baz():
 ...     BAD = 'local assignment binds locally unless global is specified'
 ...     print BAD
 ...
 >>> baz()
 local assignment binds locally unless global is specified
 >>> print BAD
 global BAD



 >>> def baz():
 ...     global BAD
 ...     BAD = 'assigned locally, but destination global instead because of "global BAD"'
 ...     print BAD
 ...
 >>> print BAD
 global BAD
 >>> baz()
 assigned locally, but destination global instead because of "global BAD"
 >>> print BAD
 assigned locally, but destination global instead because of "global BAD"



 >>> BAD = 'global BAD'
 >>> def baz(BAD=BAD):
 ...     BAD += ' -- local mod to local arg pre-bound to global BAD when baz defined'
 ...     print BAD
 ...
 >>> print BAD
 global BAD
 >>> BAD = 'changed global'
 >>> print BAD
 changed global
 >>> baz()
 global BAD -- local mod to local arg pre-bound to global BAD when baz defined
 >>> print BAD
 changed global

HTH

Regards,
Bengt Richter




More information about the Python-list mailing list