Skip to content Skip to sidebar Skip to footer

Using Var From From Function A To Function B

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

Solution 1:

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.

Solution 2:

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'])

Solution 3:

NB: untested

You could change your db_properties to return a dict:

from functools import partial

# call as db_properties('db_host', 'db_name'...)defdb_properties(self, *args):
    parser = SafeConfigParser()
    parser.read('config file')
    getter = partial(parser.get, 'database')
    returndict(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')...)

Solution 4:

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()
printconfig[0]     # db_host
printconfig.host   # same

Post a Comment for "Using Var From From Function A To Function B"