Module variables

Peter Hansen peter at engcorp.com
Wed May 28 14:23:16 EDT 2003


Cameron Zemek wrote:
> 
> Okay I have been translating some pascal into python. I need to have
> variables with module scope. atm I'm doing this with "global" in methods
> that need to update the global variable. Is there a way todo this that
> doesn't need each function to declare what global variables it will need.
> Also what is the naming convention for variables and functions that are
> internal to the module?

Answering several of the above with one approach: you could create
a "bad" object which acts as a container for all your "globals".
Name it something simple like "g" and you've also covered the naming
convention issue somewhat, by allowing any name for the "internal"
variables and "g." as a prefix for the "global" ones.

class Bag:
    pass

g = Bag()

Then modify your code like this:

> def GetChar():
>     try:
>         g.Look = g.input[g.index]
>         g.index = g.index + 1
>     except:
>         g.Look = '\n'
> 
> def Match(char):
>     if g.Look == char:
>         GetChar()
>     else:
>         Expected("'" + str(char) + "'")

etc....

I wouldn't do this personally, but it might be the simplest approach for
you to avoid having to sprinkle "global" everywhere, but to clearly 
highlight which things are global and which are local.

(The "use a class and methods" response is really the best, but if you're
translating this as a quick hack, maybe the above is enough.)

-Peter




More information about the Python-list mailing list