Loading select queries into objects

piet at cs.uu.nl piet at cs.uu.nl
Mon Jun 18 09:46:22 EDT 2001


>>>>> "Graham Ashton" <graham at coms.com> (GA) writes:

GA> Hi. I've just started playing with database access from Python and have
GA> stumbled across yet another hole in my knowledge of Python idioms.

GA> I've got a class that has an attribute for each column in a database
GA> table, and an accessor method that sets the value of each attribute. I
GA> then populate the attributes with the result of a database query.

GA> Here's an example:

GA>     query = """
GA>         SELECT column1, column2, some_column
GA>           FROM a_table
GA>     """

GA>     cursor = self.db.cursor()
GA>     cursor.execute(query)
GA>     tup = cursor.fetchone()

GA>     self.column1(tup[0])		# this could be better!
GA>     self.column2(tup[1])
GA>     self.some_column(tup[2])

GA> What I'm wondering is; is there an idiomatic way of applying the values
GA> in a tuple to a list of functions? In Perl I'd use map(), but I'm not
GA> sure if there's a "cleaner" way in Python.

If you can use map in Perl, you can use map in Python. But I don't think
this problem can be solved easily with map, because map applies a single
function to a sequence, not a list of functions to a sequence.

That is, if I understand how you want to do it:
        The list of functions is [f0, f1, f2] and you want:
        f0(tup[0])
        f1(tup[1])
        f2(tup[2])

You could do something like:
funlist = (self.column1, self.column2, self.some_column)

for i in range (len(funlist)):
        apply(funlist[i],(tup[i],))

or use zip.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl



More information about the Python-list mailing list