views:

169

answers:

1

Probably a very common question, but couldn't find suitable answer yet..

I have a (Python w/ C++ modules) application that makes heavy use of an SQLite database and its path gets supplied by user on application start-up.

Every time some part of application needs access to database, I plan to acquire a new session and discard it when done. For that to happen, I obviously need access to the path supplied on startup. Couple of ways that I see it happening:

1. Explicit arguments

The database path is passed everywhere it needs to be through an explicit parameter and database session is instantiated with that explicit path. This is perhaps the most modular, but seems to be incredibly awkward.

2. Database path singleton

The database session object would look like:

import foo.options
class DatabaseSession(object):
    def __init__(self, path=foo.options.db_path):
        ...

I consider this to be the lesser-evil singleton, since we're storing only constant strings, which don't change during application runtime. This leaves it possible to override the default and unit test the DatabaseSession class if necessary.

3. Database path singleton + static factory method

Perhaps slight improvement over the above:

def make_session(path=None):
    import foo.options
    if path is None:
        path = foo.options.db_path
    return DatabaseSession(path)

class DatabaseSession(object):
    def __init__(self, path):
        ...

This way the module doesn't depend on foo.options at all, unless we're using the factory method. Additionally, the method can perform stuff like session caching or whatnot.

And then there are other patterns, which I don't know of. I vaguely saw something similar in web frameworks, but I don't have any experience with those. My example is quite specific, but I imagine it also expands to other application settings, hence the title of the post.

I would like to hear your thoughts about what would be the best way to arrange this.

+2  A: 

Yes, there are others. Your option 3 though is very Pythonic.

Use a standard Python module to encapsulate options (this is the way web frameworks like Django do it)

Use a factory to emit properly configured sessions.

Since SQLite already has a "connection", why not use that? What does your DatabaseSession class add that the built-in connection lacks?

S.Lott
Thanks for comment. I used term "database session" to simplify the example; in reality, its more like an object factory which gets its blueprints from database.
Dimitri Tcaciuc