[Tutor] advice on global variables

Walter Prins wprins at gmail.com
Wed Jul 11 15:05:55 CEST 2012


Hi,

On 11 July 2012 01:31, Chris Hare <chare at labr.net> wrote:
> Thanks Alan -- I am thinking I am just gonna go with the RAM based SQLite database ….

That seems an awfully large hammer for a little global variable
problem.  Why can you not (as a start) just move the global(s) into
their own namespace/location that's readily accessible i.e. can be
simply imported where needed/referenced.  In other words as has
essentially been suggested, make a module containing the global
variables directly (or perhaps as part of a class or object that can
act as a container for them) ?    (To be a little more direct: I don't
think a RAM based SQLite database will really do anything for you
beyond what a little shared module/class/object won't already do in
terms of dealing with a global variable problem, and will instead
really just add needless complexity to your program. There is a time
and place for in-memory databases but this is IMHO not really it.)

Your original example modified as demonstration:

a.py:
====
import shared
import b

def func1():
        print "global var in func1 = %s" % shared.global_var

class intclass:
        def func2(self):
                print "global var in intclass = %s" % shared.global_var

print "global_var = %s" % shared.global_var
func1()
f = intclass()
f.func2()
g = b.extclass()
g.func3()

b.py:
====

import shared

class extclass:
        def func3(self):
                print "global var in extclass = %s" % shared.global_var


shared.py:
=======
global_var = "global"

Walter


More information about the Tutor mailing list