Global variables for python applications

Giampaolo Rodolà g.rodola at gmail.com
Mon May 17 19:33:52 EDT 2010


2010/5/16 Chris Rebert <clp2 at rebertia.com>:
> On Sun, May 16, 2010 at 10:50 AM, AON LAZIO <aonlazio at gmail.com> wrote:
>> Hi,
>>    How can I set up global variables for the entire python applications?
>> Like I can call and set this variables in any .py files.
>>    Think of it as a global variable in a single .py file but this is for the
>> entire application.
>
> Thankfully, there is no such thing (can you say spaghetti code?). The
> closest approximation, as I said in my previous reply, is to use the
> namespace of a designated module for this purpose, and import that
> module wherever you need to access/modify these "superglobal"
> variables.
>
> Example:
> #g.py:
> #this module exists to hold superglobal vars
> global1 = "foo"
> global2 = "bar"
>
>
> #elsewhere.py:
> #this is some other module in the same program
> import mypackage.g as g
>
> print "global #1 = ", g.global1
> print "global #2 =", g.global2
> g.global1 = "baz" # modify a superglobal
> g.global3 = "qux" # create a new superglobal
>
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
> --
> http://mail.python.org/mailman/listinfo/python-list

I agree global variables are evil, but a config.py module within a
serie of global constants which are supposed to be shared amongst all
other modules is a little less evil, and also a different beast IMO.
Even if you use a class to store such data, a "global" reference to
its instance accessible from everywhere must still exist, so the
problem basically still stands.
I would be interested to know a good practice to solve such a problem.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil



More information about the Python-list mailing list