jramm
jramm

Reputation: 6655

python: encapsulate data without a class?

I have a module in python that provides various functions for performing database queries. It looks like this:

def do_some_query(conn):
    ## logic goes here

def do_something_else(conn):
    ## logic goes here

Where conn is a database connection object. Of course, this means a lot of passing around of the conn object. I'd like to allow the user to just set the connection object once for their session and then call the functions.

OBVIOUSLY putting the whole thing in a class is a good answer, but I dont want to have to make the user initialise a class each time they want to use the functions. I.E, I dont want the API to be like this:

 from database_module import DatabaseClass

 db = DatabaseClass()
 db.connect(...)
 db.do_some_query()

But like this:

 import database_module as dm

 dm.connect(...)
 dm.do_some_query()

Is there a way to either 'hide' the class from a user, or provide encapsulation without the class?

Upvotes: 0

Views: 262

Answers (1)

zmbq
zmbq

Reputation: 39013

You can have a connect function that puts the connection in a global variable, and the other functions will use it.

_conn = None

def connect():
    global _conn
    _conn = ...

def query():
    _conn.execute("SELECT ...")

Upvotes: 1

Related Questions