Global variables for python applications

TomF tomf.sessile at gmail.com
Wed May 19 03:16:56 EDT 2010


On 2010-05-16 12:27:21 -0700, christian schulze said:

> On 16 Mai, 20:20, James Mills <prolo... at shortcircuit.net.au> wrote:
>> On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund
>> 
>> <krister.svanl... at gmail.com> wrote:
>>> On Sun, May 16, 2010 at 7:50 PM, AON LAZIO <aonla... at gmail.com> wrote:
>>>>    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 thisis for the
>>>> entire application.
>> 
>>> First: Do NOT use global variables, it is bad practice and will
>>> eventually give you loads of s**t.
>> 
>>> But if you want to create global variables in python I do believe it
>>> is possible to specify them in a .py file and then simply import it as
>>> a module in your application. If you change one value in a module the
>>> change will be available in all places you imported that module in.
>> 
>> The only place global variables are considered somewhat "acceptable"
>> are as constants in a module shared as a static value.
>> 
>> Anything else should be an object that you share. Don't get into the
>> habit of using global variables!
>> 
>> --james
> 
> Exactly! Python's OOP is awesome. Use it. Global vars used as anything
> but constants is bad practice. It isn't that much work to implement
> that.

Let's say you have a bunch of globals, one of which is a verbose flag.  
If I understand the difference, using a module gbls.py:
# in gbls.py
verbose = False
# elsewhere:
import gbls
gbls.verbose = True

Using a class:

# In the main module:
class gbls(object):
	def __init__(self, verbose=False):
		self.verbose = verbose

my_globals = gbls.gbls(verbose=True)
...
some_function(my_globals, ...)


If this is what you have in mind, I'm not really seeing how one is good 
practice and the other is bad.  The OOP method is more verbose (no pun 
intended) and I don't see how I'm any less likely to shoot myself in 
the foot with it.

-Tom





More information about the Python-list mailing list