initialization in python

Terry Reedy tjreedy at udel.edu
Thu Jan 1 13:14:17 EST 2009


koranthala at gmail.com wrote:

>>> Module database:
>>> ^^^^^^^^^^^^^^^^^^^
>>> Session = None

'Initializing' names is not necessary.  Delete this.  Without it, your 
error would be more obvious.

>>> def init(dbname):
>>>    engine = create_engine('sqlite:///%s' %dbname)
>>>    ...
>>>    global Session
>>>    Session = sessionmaker(bind=engine)

This **rebinds* the module name 'Session' to a new object, making the 
initial bindin irrelevant and misleading.

[snip]
> 
> I guessed as much. But, I was under the impression that if the
> original value is modified, the variables value also will change.

Python has names and slots bound to objects.  Some objects are mutable 
and some not.  None is not mutable.  You replaced it.

If you had done something like

Session = sessionmaker()

def init(dbname):
     Session.engine = create_engine('sqlite:///%s' %dbname)
     ...

then you would have *modified* the original object (value) bound to 
'Session' and would have seen the behavior you expected.

Terry Jan Reedy




More information about the Python-list mailing list