I must be an idiot, please pity me!

laotseu bdesth at nospam.free.fr
Sat Sep 14 00:21:13 EDT 2002


newbie wrote:
> On Thu, 12 Sep 2002 01:25:59 +0100, laotseu wrote:
> 
> 
> 
>>Creating a db connection in each function for sure not be very
>>efficient.But what's wrong with passing the database connection to the
>>functions in mod1, mod2, and modXXX ???
> 
> 
> That connection has to be passed to the other functions (where needed of
> course) in mod1. Say, mod1.functiona may use functions f1, f2 and f3. My
> gut feeling of having to pass that connection to all of these said "this
> can't be right". This is what I've done but it sure doesn't feel right!
> 
> 
> 
>>Anyway, you can make it simpler, like this :
> 
> 
> Yay, now for the good stuff!
> 
>  
> 
>>in each module,
>>- create a global db_connection variable - add an init() function, that
>>takes a db_connection as argument and assign it to the module's global
>>db_connection variable - and don't forget to call this function before
>>any other.
> 
> 
> Yes, I can follow that. Once I saw that "global" was more "local" I've
> never really considered using it.

??? Not clear what you mean ???

> 
> 
>>Another, more OO way to do this would be to rewrite your modules as
>>classes, each getting a db_connection argument in it's __init__(), and
>>then, in the main script, create the needed objects.
> 
> 
> So the resulting object would be the same as what I return with now?
> 

A simple exemple is better than a long explanation :

# this was your module mod3

import whateverYouHaveToImport

class Mod3:
     def __init_(self, dbConnection):
         self.dbConnection = dbConnection
         # add what you need here

     def f1(args):
         something = self.dbConnection.doThis(args)
         return self.f2(something)

     def f2(args):
        return self.dbConnection.doThat(args)


# this is you GCI module

import mod3
import TheRest

def main():
     dbConnection = dbModule.CreateMyDbConnection(args)
     m3 = Mod3(dbConnection)
     this = m3.f1(42)



Got it ?

HTH
Laotseu




More information about the Python-list mailing list