2

Looking to have a database query set all the instance variables in a class:

Example:

def populate(self, if):
    #Perform mysql query

    self._name = row['name']
    self._email = row['email']
    ...

What's the fastest way to do this? Or is this not recommended (with a better approach)?

2 Answers 2

4
  • It makes your code the most readable and predictable to do it manually like this. That way you know exactly what attributes exist and what attributes do not pretty easily.

  • You can use setattr to automate tons of these.

    One fairly nice way would be to define a list attributes = ['name', 'email'...] as a class attribute then to do

    for name in self.attributes:
        setattr(self, "_" + name, row[name])
    

    You also can get the attributes from the query itself, but this will change depending on your query (especially if you're using SELECT * or anything like that) and your changing your database.

  • I notice these attributes all have leading underscore. If this is a purely internal thing, consider whether an attribute rather than the query result itself or storing a dict wouldn't better suit your needs. Generally, attributes are supposed to be fairly static things.

  • I hear oursql is nicer the MySQLdb

4
  • Thanks, Mike. This was very helpful. What do you mean by your second to last point about the query result itself a dict? Do you mean setting an instance variable like "info" and just setting the entire row equal to that? row = db.getRow(query) self._info = row something like that?
    – ensnare
    Mar 30, 2010 at 5:09
  • @ensnare, That is exactly what I mean. Mar 30, 2010 at 5:43
  • Would it be weird to have a discrepancy in that case between user.id and user.info.id? What is a cleaner solution? Thanks for your help.
    – ensnare
    Mar 30, 2010 at 5:45
  • You may or may not also want to set all the other stuff directly as attributes. If you opened a new question explaining the problem you are solving, someone might be able to help you be sure you have the optimal design for your class. Mar 30, 2010 at 6:45
3

Look at sqlalchemy it's the most popular database abstraction for python.
If you really like the active record pattern there is a layer you can put on top of it called elixir.

I use sqlalchemy because it's a nice database abstraction and allows me to switch out databases. I use sqlite in memory for my tests and I can wedge it in to my code using sqlalchemy.

1
  • Thanks for the response. I used sqlalchemy for a bit, but since I'm not interested in database portability it seemed a little heavyweight for what I was trying to do.
    – ensnare
    Mar 30, 2010 at 5:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.