The global statement

Mel Wilson mwilson at the-wire.com
Wed Jul 23 13:45:16 EDT 2003


In article <pan.2003.07.23.15.14.52.430267 at intnet.mu>,
"David Hitillambeau" <edavid at intnet.mu> wrote:
>On Wed, 23 Jul 2003 16:56:08 +0200, Thomas Güttler wrote:
>
>> If foo and bar are in the same file,
>> you don't need the "global".
>
>Then when is "global" required? What is it's role?

   More to the point, maybe (although it doesn't do much):


global_var = 27

def f1():
    global global_var
    if global_var % 2 == 1:
        global_var = 3 * global_var + 1

def f2():
    global global_var
    while global_var % 2 == 0:
        global_var /= 2

def f3():
    return (global_var != 1)

while f3():
    print global_var,
    f1()
    print global_var,
    f2()
    print global_var


where f1 and f2 will behave very differently if the `global`
statements are removed.  Normally, any time code inside a
function assigns to a symbol, it does it in the functions
local namespace.  In these cases, there'll be a compiler
error.

   Because f3 doesn't assign to global_var, it doesn't need
the `global` statement.  That is, the *only* global_var that
f3 could possibly access is the "global" one.
   You could include a global statement for documentation's
sake if that were your taste.

   And of course global_var is local as far as the `print`
statements are concerned.


        Regards.        Mel.




More information about the Python-list mailing list