[Tutor] advice on global variables
Alan Gauld
alan.gauld at btinternet.com
Wed Jul 11 01:16:07 CEST 2012
On 10/07/12 20:11, Chris Hare wrote:
> I know they are bad.
They are not totally bad and most real programs wind up
having one or two globals, although usually those globals
are top level container classes, perhaps even an Application
class or similar.
> I am not sure how else to handle this problem.
Others have given lots of ideas but, by way of summary,
there are several common strategies:
1) Use function parameters. Your coding style seems to favour empty
parameter lists. That's a bad idea. Pass values into functions as
arguments and return values
def myfunc(n):
return n+1
foo = 42
foo = myfunc(f00)
rather than
def myfunc():
global foo
foo += 1
myfunc()
It avoids hidden, and therefore forgotten, side effects, makes your
function usable with variables other than foo and is often less code too.
2) Move the "global" data plus all the functions that access it into a
class:
class MyFuncs
def __init__(self, n)
self.foo = n
def myfunc(self):
self.foo += 1
m = MyFuncs(42)
m.myfunc()
Same effect as above but encapsulated in a class so you can create
multiple instances each with its own value of foo. And you can pass the
whole class/object around as an argument to other functions (see
technique 1 above) And you can put it in a module to make the class
available in other modules.
3) Move all global data into a single module which is then imported by
any module that needs to access it . This avoids circular dependencies,
By combining these strategies you can minimise the number of globals,
isolate them in a single module without dependencies and by making the
few globals into class instances keep control of the data access.
> One thought was a RAM based SQLite database, but that seems
> like a lot of work. I dunno, maybe that is the option.
It is an option, and for things like user ID etc its a valid one. This
is definitely the best option where the "global" needs to be shared
across different programs as well as different modules in a single
program. But it is more work.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list