Problem with global

Larry Bates larry.bates at websafe.com
Fri Oct 12 16:54:47 EDT 2007


Florian Lindner wrote:
> Hello,
> I have a little problem with the global statement.
> 
> def executeSQL(sql, *args):
>     try:
>         import pdb; pdb.set_trace()
>         cursor = db.cursor()  # db is <type 'NoneType'>.
>         [...]
>     except:
>         print "Problem contacting MySQL database. Please contact root."
>         sys.exit(-1) 
> 
> 
> db  = None # Global Variable for DB connection
>     
> def main():
>     [...]    
>     global db
>     db = MySQLdb.connect(...)
>     [...]
>     executeSQL(sql, args)
> 
> 
> Why isn't the global variable db not written in main() to be a mysql
> connection and still none type in executeSQL?
> 
> Thanks,
> 
> Florian

Because you have it to let executeSQL know that it is global or it creates a 
local copy in local namespace.

def executeSQL(sql, *args):
     global db
     try:
         import pdb; pdb.set_trace()
         cursor = db.cursor()  # db is <type 'NoneType'>.
         [...]
     except:
         print "Problem contacting MySQL database. Please contact root."
         sys.exit(-1)

-Larry



More information about the Python-list mailing list