Simple question about variables

Gerhard Häring gerhard.haering at gmx.de
Sun Dec 1 09:46:43 EST 2002


Michel COMBE wrote:
> I have a program which is made of 3 phases :
> 1. Read record set from MySQL
> 2. Process the data read
> 3. Write the result of the process to a file
> 
> I would like the 3 phases to be 3 procedures.
> How can I manage to have the record set declared globally so that I can use
> it from all 3 procedures ?
> (Right now, it is declared locally in the first procedure by the statement
> result=cursor.fetchall )

Wojtec described how to do what you asked for. Let me just add that in
precisely 99.257 % of all cases, global variables are a bad thing.

You're usually better off with using functions (and classes, once
you've become familiar with structured programming using functions).

The steps 1 to 3 you described fit *very well* to a program using
functions. Here's a draft:

#v+
import MySQLdb

def readRecord():
    conn = MySQLdb.connect(...)
    cursor = conn.cursor()
    cursor.execute("SELECT ...")
    recordset = cursor.fetchall()
    conn.close()
    return recordset

def processData(recordset):
    # do stuff with recordset, then return the result
    # ...
    return result

def writeToFile(data):
    # ...

# Now if you've put your logic into functions and each function
# returns the result of each step, while getting the input as a
# parameter (NO global variables involved), you can simply join these
# functions like this:

writeToFile(processData(readRecord()))
#v-

-- Gerhard



More information about the Python-list mailing list