views:

95

answers:

2

Should I access global db object directly from within the methods of each class? Or from each method, should I instantiate an instance of the db object?

One of my database objects changes depending on the id of the info being accessed so it is created through a function connectToDatabase(id). Should I make this a global function, have it return a database object and instantiate it from each method, or something else?

Thanks.

+2  A: 

In this case, like in many others, I prefer dependency injection: have your class (e.g in its __init__) accept the DB connection as an argument.

This makes it easier and cleaner to test, lets you switch strategies as needed (e.g. to move to a "pool of DB connections" strategy if you find otherwise you're making too many DB connections at once), and distributes responsibilities more accurately and flexibly.

In general, I think of Dependency Injection as probably the most important Design Pattern that was not listed in the great "Gang of 4" book!-)

Alex Martelli
+1  A: 

SQLAlchemy suggests that a function which creates the session be global.

http://www.sqlalchemy.org/docs/reference/orm/sessions.html#sqlalchemy.orm.sessionmaker

It is intended that the sessionmaker() function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions.

S.Lott