initialization in python

John Machin sjmachin at lexicon.net
Thu Jan 1 08:54:42 EST 2009


On Jan 1, 11:44 pm, koranth... at gmail.com wrote:
> How does an average product handle initialization in python?
> I am facing lot of issues in handling initialization, especially if I
> import specific variables, due to the variables not getting updated.
>
> For example - taking a sqlalchemy based product:
> Module database:
> ^^^^^^^^^^^^^^^^^^^
> Session = None
>
> def init(dbname):
>    engine = create_engine('sqlite:///%s' %dbname)
>    ...
>    global Session
>    Session = sessionmaker(bind=engine)
>
> In entry module to the application (APPENTRY):
> ^^^^^^^^^^^^^^^^^^^
> import A, B, C, D  <---- Please note, very important
> ....
> ....
> database.init('testdb.db')
>
> Now in user module A:
> ^^^^^^^^^^^^^^^^^^^^^^^^^^
> from database import Session
> print Session
> --->This will print None, because at APPENTRY, during importing A
> itself, Session is stored.

This is happening when you import A, which happens *before* you call
database.init(). database.init binds the name database.Session to a
new value. The name A.Session has been bound earlier to the value
None.

> I have to call database.Session to get the values.

I don't understand that sentence. Is database.Session callable (i.e.
is a function or class)? What valueS (plural)?

> Why is the variable not getting updated?

Firstly, it's not a "variable" in the sense of a named slice of memory
to which various values can be assigned.

Secondly, it could be updated only if the "from database import
Session" operated like it was creating an alias e.g.
    A.Session isanaliasof database.Session
like a C macro
    #define A_Session database_Session
but it isn't; its effect is that of a fancy "assignment", more or less
like:
    import database
    Session = database.Session
    del database

In any case, mucking about with module globals like you are trying to
do is not a good idea. As you have seen, it introduces dependencies
like you need to import A after the database is initiated. As soon as
you need more than one session at a time, or the single session needs
to be closed and restarted, it really falls apart. Try passing your
session around as a function arg, or as an attribute of an object that
contains current state information.

HTH,
John



More information about the Python-list mailing list