1

On this sample code i want to use the variables on the function db_properties at the function connect_and_query. To accomplish that I choose the return. So, using that strategy the code works perfectly. But, in this example the db.properties files only has 4 variables. That said, if the properties file had 20+ variables, should I continue using return? Or is there a most elegant/cleaner/correct way to do that?

import psycopg2
import sys
from ConfigParser import SafeConfigParser

class Main:

    def db_properties(self):
        cfgFile='c:\test\db.properties'
        parser = SafeConfigParser()
        parser.read(cfgFile)
        dbHost = parser.get('database','db_host')
        dbName = parser.get('database','db_name')
        dbUser = parser.get('database','db_login')
        dbPass = parser.get('database','db_pass')
        return dbHost,dbName,dbUser,dbPass

    def connect_and_query(self):
        try:
            con = None

            dbHost=self.db_properties()[0]
            dbName=self.db_properties()[1]
            dbUser=self.db_properties()[2]
            dbPass=self.db_properties()[3]

            con = None
            qry=("select star from galaxy")
            con = psycopg2.connect(host=dbHost,database=dbName, user=dbUser,
                                   password=dbPass)
            cur = con.cursor()
            cur.execute(qry)
            data = cur.fetchall()
            for result in data:
                qryResult   = result[0]
                print "the test result is : " +qryResult
        except psycopg2.DatabaseError, e:
                print 'Error %s' % e
                sys.exit(1)
        finally:
            if con:
                con.close()

operation=Main()
operation.connect_and_query()

Im using python 2.7 Regards

4 Answers 4

5

If there are a lot of variables, or if you want to easily change the variables being read, return a dictionary.

def db_properties(self, *variables):
    cfgFile='c:\test\db.properties'
    parser = SafeConfigParser()
    parser.read(cfgFile)
    return {
        variable: parser.get('database', variable) for variable in variables
    }

def connect_and_query(self):
    try:
        con = None
        config = self.db_properties(
            'db_host',
            'db_name',
            'db_login',
            'db_pass',
        )
        #or you can use:
        #   variables = ['db_host','db_name','db_login','db_pass','db_whatever','db_whatever2',...]
        #   config = self.db_properties(*variables)
        #now you can use any variable like: config['db_host']
        # ---rest of the function here---

Edit: I refactored the code so you can specify the variables you want to load in the calling function itself.

8
  • +1, but note that dictionary comprehensions don't work in Python <= 2.6; dict((variable, parser.get(variable)) for variable in variables) would be portable to older versions.
    – Fred Foo
    Oct 4, 2012 at 15:40
  • Actually that's a good point to remember whenever writing dictionary comprehensions. Thanks for pointing it out :)
    – Anuj Gupta
    Oct 4, 2012 at 15:43
  • @AnujGupta I tried you solution and i received the error: "TypeError: get() takes at least 3 arguments (2 given)
    – thclpr
    Oct 4, 2012 at 15:59
  • Need to also pass 'database' to parser.get(), that's all :) I've updated the code.
    – Anuj Gupta
    Oct 4, 2012 at 16:02
  • 1
    Yes, but this revision is the direct answer to your exact question. If you want, you can revise your question to include the multi-section problem and I'll move this back to revision 8.
    – Anuj Gupta
    Oct 4, 2012 at 18:10
4

You certainly don't want to call db_properties() 4 times; just call it once and store the result.

It's also almost certainly better to return a dict rather than a tuple, since as it is the caller needs to know what the method returns in order, rather than just having access to the values by their names. As the number of values getting passed around grows, this gets even harder to maintain.

e.g.:

class Main:
    def db_properties(self):
        cfgFile='c:\test\db.properties'
        parser = SafeConfigParser()
        parser.read(cfgFile)
        configDict= dict()
        configDict['dbHost'] = parser.get('database','db_host')
        configDict['dbName'] = parser.get('database','db_name')
        configDict['dbUser'] = parser.get('database','db_login')
        configDict['dbPass'] = parser.get('database','db_pass')
        return configDict

    def connect_and_query(self):
        try:
            con = None
            conf = self.db_properties()

            con = None
            qry=("select star from galaxy")
            con = psycopg2.connect(host=conf['dbHost'],database=conf['dbName'],
                                   user=conf['dbUser'],
                                   password=conf['dbPass'])
1
  • Could you give me an example of how i could do that please?
    – thclpr
    Oct 4, 2012 at 15:27
0

NB: untested

You could change your db_properties to return a dict:

from functools import partial

# call as db_properties('db_host', 'db_name'...)
def db_properties(self, *args):
    parser = SafeConfigParser()
    parser.read('config file')
    getter = partial(parser.get, 'database')
    return dict(zip(args, map(getter, args)))

But otherwise it's probably best to keep the parser as an attribute of the instance, and provide a convenience method...

class whatever(object): def init(self, *args, **kwargs): # blah blah blah cfgFile='c:\test\db.properties' self._parser = SafeConfigParser() self._parser.read(cfgFile) @property def db_config(self, key): return self._parser.get('database', key)

Then use con = psycopg2.connect(host=self.db_config('db_host')...)

0

I'd suggest returning a namedtuple:

from collections import namedtuple

# in db_properties()
return namedtuple("dbconfig", "host name user password")(
             parser.get('database','db_host'),
             parser.get('database','db_name'),
             parser.get('database','db_login'),
             parser.get('database','db_pass'),
       )

Now you have an object that you can access either by index or by attribute.

config = self.db_properties()
print config[0]     # db_host
print config.host   # same

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.