global declaration from within functions

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Aug 15 12:16:32 EDT 2001


Joshua Marshall <jmarshal at mathworks.com> wrote in
news:9le69l$bha$1 at news.mathworks.com: 

>> The 'global' keyword doesn't create a new global variable. All it does
>> is to force references to that name, within that local scope, refer to
>> a global variable. If you assign to the variable declared as global
>> then you will update its value. If you reference the variable then you
>> get its value if it exists, or you get an exception if it doesn't
>> exist. 
> 
> No, Rob is right:
> 
>  >>> def f():
>   ...    global x
>   ...    x = 666
>   ... 
>  >>> f()
>  >>> x
>   666
> 
> You can use 'global' to define a new variable.
> 
But the global keyword did not create the variable. The assignment to the 
variable created it. You can use the 'global' keyword and still not have 
the variable created, you can also create a global variable without using 
the keyword (e.g. by setting a value in the result of globals()).

The global keyword simply changes how the name is used within a local 
scope. It does not, of itself, create a global variable. A global variable 
is created by assigning to it either directly from outside a function/class 
body; assigning to it from inside a function before(!) or after the use of 
a matching 'global' statement; or assigning to it indirectly such as 
through globals().

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list