global declaration from within functions

Alex Martelli aleaxit at yahoo.com
Wed Aug 15 11:58:28 EDT 2001


"Rob Andrews" <rob at jam.rr.com> wrote in message
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.

Typically as a shortcut to avoid making a class &c, as in:

_totalcount = 0
def addwords(words_string):
    global _totalcount
    _totalcount += len(words_string.split())
def getcount():
    return _totalcount

as a rough equivalent of:

class Counter:
    def __init__(self):
        self._counter = 0
    def addwords(self, words_string):
        self._counter += len(words_string.split())
    def getcount(self):
        return self._counter
_counter = Counter()
addwords = _counter.addwords
getcount = _counter.getcount

There are other idioms yet for this, of course, but the rough & ready
one that global allows can still be handy when hacking something
together, although most often you'll want to refactor it away into a
class when prettying up your code after a session of interactive
development (but not always, depending on individual style).


> 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."

Python has no declarations -- the global statement may seem to come
close, but it IS technically a statement.  It tells the compiler "although
local is the default for variables locally bound or re-bound, for this one
I want you to make an exception please -- let it be global instead".

There being no declarations at all, of course there aren't, in particular,
any declarations that have to be "outside the scope of any functions".
The global statement has to be INSIDE the scope of each function to
which it applies, because any function lacking it will use the default
rule of seeing as local any variable it binds or rebinds.

Having to tag as global, explicitly, any global variable your function
needs to bind or re-bind, is, I think, a good way to discourage the
overuse of global variables while keeping them available for those
who prefer them, and therefore quite a Pythonic thing.


Alex






More information about the Python-list mailing list