global variables extended to other objects/modules

KN vald at dead.art.pl
Fri Apr 16 18:50:06 EDT 2004


Hello, I'm new to this list, and I have an important
question at the beginning.

There is a matter that concerns me - it's the globales
implementation. I've read nearly everything I found 
about this and about problems people were having with
using it.

And now I'd like to ask here, because it seems to be
more than globales() matter, but an object-programming
one. I don't know any patterns for solving such problems.
Actually I'm working on an web application based on
mod_python, but this is not very important here. I use
MVC patterns for application flow, so I have one object
that works as handler and controller, and this object
creates Action-classes which run all necessary business
logic by creating other objects that for example fetch
information from database. You probably know what I need
to do here - I need a link to the database that will be
accessible from _every_ module and object that needs to
use it. 

I wanted it to be started and closed by main module -
controller.py. Main area where I will use it will be 
a bunch of small model-objects, like Person/Store etc.
classess that fetch data from db, saves them, return
them to Action object which passess them back to the
controller etc.

Now, when I cannot have a really global attributes that
will be accessible even for objects imported from 
different modules, only way I see is to pass it in
constructors, so:

  controller.py  -> Action.__init__(dblink)

  then in Action I need to use Person and Job classess
  that both need db access:

  action.py -> Person.__init__(dblink), Job.__init__(dblink)

and so on.

Is this a common way of solving this problem? What I 
don't want for sure is multiple connections per request
so I need a single object storing db_link. Is there 
any solution that will not force me to pass this reference
to every object I create, when I need db access?

I thought something about using globals() there and I
found that I can use sys.modules for getting the main
object (controller) from any other module. 

  when I define in controller.py which is __main__
  something like global db = DBlink()

  I can use in any module something like this, right?
  
  local_db_link = sys.modules['__main__'].db 

  and I will get reference to this link created on the
  beginning of application?

But this seems to be ugly and not very object-oriented?

The problem wouldn't be so big if I hadn't so many 
attributes I need to pass to most of my objects, like
request, session, configuration and other attribs that
should be 'application-wide'
It would be very bad to define in every object __init__
which will have so many arguments.

Best regards,
Kamil


  





More information about the Python-list mailing list