[Tutor] Why a global?

Christopher Arndt chris.arndt at web.de
Wed Dec 27 14:26:36 CET 2006

Carlos schrieb:
> My problem is that no matter were I put this, I have to declare ga a 
> global.

You are confusing two different objects with the name 'ga' here:

a) the module object 'ga' which you create by import ing it:

import ga

this binds the name 'ga' to the module object created by reading in the 
module ga (probably some file name 'ga.py' or a package).

b) The instance object of the the 'GA' class you create with

ga = ga.GA(pop = 2, alleles = range(10), gene_size = 8)

You have named the variable that holds a reference to this instance 
object b) also 'ga' thereby *overwriting the global variable 'ga'*, 
which held a reference to the module object a).

If you want to overwrite a global variable in a function, you have to 
declar it global with the 'global' keyword.

*But that's not what you want here.*  Just give another name to your 
instance variable:

import ga

def runGA(pop, gen, it):
     ga_inst = ga.GA(pop = 2, alleles = range(10), gene_size = 8)
     ga_inst.debug = 1

HTH, Chris

More information about the Tutor mailing list