changing a var by reference of a list

Carsten Haese carsten at uniqsys.com
Tue May 8 10:18:34 EDT 2007


On Tue, 2007-05-08 at 15:40 +0200, Jorgen Bodde wrote:
> Ok thanks,
> 
> I will try this approach. The idea was that I could give a list to the
> SQL execute command, so that the results coming back would
> automatically be assigned to variables.

It's not possible to do that exactly as stated. A function can not
modify its caller's namespace. (There is probably some dirty trick that
can do this anyway, but you don't want to use dirty tricks.) Also, I'm
not sure I'd want a function to pollute my local namespace with any
variables of its choice. How would I know that it won't overwrite any
variable whose contents I need? (Don't try to answer, this is a
rhetorical question!)

Most DB-API implementations have a facility to return query results as
dictionaries or "a bag full of attributes"-type objects. The syntax for
achieving this varies between implementations, because this is a
non-standard addition outside the DB-API spec. With InformixDB for
example, it would look something like this:

import informixdb
conn = informixdb.connect("stores_demo")
cur = conn.cursor(rowformat=informixdb.ROW_AS_OBJECT)
cur.execute("select * from customer")
for row in cur:
   print row.customer_num, row.company

This allows accessing the result columns as attributes of a row object,
which is 99% as convenient as having local variables assigned to the
results, and its 15000% cleaner.

I strongly suggest you find an equivalent mechanism to use with whatever
database module you're using, since it's a fairly safe bet that you're
not using Informix. We could help you find that mechanism if you told us
what database and what DB-API module you're using.

Best regards,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list