global declaration from within functions

Skip Montanaro skip at pobox.com
Wed Aug 15 13:05:16 EDT 2001


    >>> def f():
    ...    global x
    ...    x = 666
    ... 
    >>> f()
    >>> x
    666

Not quite:

    >>> def f():
    ...   global x
    ...   return
    ... 
    >>> f()
    >>> x
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: name 'x' is not defined

The global declaration does not guarantee a global object will be created,
only that if you assign a value to the declared name in the current scope,
the global namespace will be modified, not the local namespace.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list