I must be an idiot, please pity me!

holger krekel pyth at devel.trillke.net
Wed Sep 11 19:21:51 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.

one common idiom is to do

    import mydb
    ... use mydb.connection ...

and somewhere at initialization time

    import sys
    class mydb:
        connection = ...  # initialize it
    sys.modules['mydb']=mydb

'import' imports always the same object. Usually it's a 
module-object but can you put in your class/type.

of course you can also simply define a module 'mydb.py' in a 
file and import that everywhere.  Besides not having another file 
the above solution makes it quite impossible to use the module/class 
before it is initialized.

regards,

    holger




More information about the Python-list mailing list