[Python-Dev] replacing 'global'

Dave Brueck dave at pythonapocrypha.com
Wed Oct 22 13:07:38 EDT 2003


> > How about
> >
> >     __.x = 42
>
> Too much line-noise, so too Perlish. :-)
>
> I don't like to use a mysterious symbol like __ for a common thing
> like a global variable.  I also don't think I want global variable
> assignments to look like attribute assignments.

Go easy on me for piping up here, but aren't they attribute assignments or
at least used as such? After reading the other posts in this thread I wonder
if it would be helpful to have more information on how "global" is used in
practice (and maybe some of those practices will be deemed bad, who knows).
>From my (a user of Python) perspective, "global" has two uses:

1) Attaching objects to the module, so that other modules do a module.name
to get at the object
2) Putting objects in some namespace visible to the rest of the module.

Now whether or not #1 is "good" or "bad" - I don't know, but it sure looks
like attribute assignment to me. Again, please regard this as just feedback
from a user, but especially outside of the module it looks and acts like
attribute assignment, I would expect the same to be true inside the module,
and any distinction would seem arbitrary or artificial (consider, for
example, that it is not an uncommon practice to write a module instead of a
class if the class would be a singleton).

As for #2, I personally don't use global at all because it just rubs me the
wrong way (the same way it would if you removed "self." in a method and made
bind-to-instance implicit like in C++). Instead, many of my modules have
this at the top:

class GV:
  someVar1 = None
  someVar2 = 5

(where GV = "global variables")

I felt _really_ guilty doing this the first few times and I continue to
thing it's yucky, but I don't know of a better alternative, and this
approach reads better, especially compared to:

global foo
<more than a few lines of code>
foo = 10

Seeing GV.foo = 10 adds a lot to readability.

>From this user's perspective, both problems #1 and #2 would be solved by an
object named "module" that refers to this module (but please don't name it
"global" or "globals" - that word has a different expected meaning).

Shutting up,
-Dave




More information about the Python-Dev mailing list