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)?
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
setattrto automate tons of these.One fairly nice way would be to define a list
attributes = ['name', 'email'...]as a class attribute then to doYou 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