global variables: to be or not to be

Matt Nordhoff mnordhoff at mattnordhoff.com
Fri Feb 22 23:01:43 EST 2008


icarus wrote:
> I've read 'global variables' are bad.  The ones that are defined as
> 'global' inside a function/method.
> 
> The argument that pops up every now and then is that they are hard to
> keep track of.  I don't know Python well enough to argue with that.
> Just started learning it a few days ago, so I won't get into
> philosophical questions such as "why this? Why not that?".  I'll take
> it as it is, just like I take 1 + 1 = 2 for granted.
> 
> So..."global variables taste bad.  Avoid them."
> 
> But how do I get around it? How do I update and access a variable
> anytime I want? Any easy-to-follow examples? Thanks in advance.

If doing everything inside one function doesn't work, you should use a
class to store state.

Here's a made-up example. Say you create a Python module to make HTTP
request. It stores the URL of the current one in a global variable. But
then anyone who uses your module can only work with one request at a
time. Instead, you should use an object called "HTTPResponse" or
something with an "url" attribute.

I don't know about other languages, but in Python, classes are very easy
to work with, so it should be no big deal. (Well, you may want to change
if your object evaluates to True, or if it's greater or smaller than 20,
or what happens when someone calls str() on it . . .  But you usually
shouldn't need to bother with all that.)
-- 



More information about the Python-list mailing list