global declaration from within functions
Duncan Booth
duncan at NOSPAMrcp.co.uk
Wed Aug 15 11:22:28 EDT 2001
Rob Andrews <rob at jam.rr.com> wrote in news:3B7A87D8.6F75B13F at jam.rr.com:
> I just posted this to the Python Tutor list, so please forgive the
> cross-posting. I'm just academically curious about this.
>
> *Learning Python* (pp. 99-105) points out that declaring globals from
> within functions is possible, and shows how. I'm trying to think of
> *why* one might want to declare or modify a global from within a
> function.
You are confused over what the 'global' keyword actually does.
Most languages, as you say, require you to declare global variables outside
functions. Most languages also require you to declare variables. Python
does not require you to declare any variables anywhere (even global ones),
instead you just assign to them.
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.
In other words the 'global' keyword is a purely local declaration that says
you want to refer to a global variable. Without the global keyword you can
still get the value of a global variable, but you cannot set the variable.
>
> A friend who knows quite a bit more than I do about the subject said:
> "That's the first thing about python I've seen that really makes me go
> "yecchhh.". Global variables have to be declared outside the scope of
> any functions or methods in almost every langauge except Perl."
Yes, but they may be assigned to or modified from inside functions in
almost every language. Python is no different here, the only difference
being that in Python you have to make it explicit that the variables you
are modifying are global whereas most other languages do it implicitly.
--
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