0

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?

asked Jan 7, 2015 at 16:22

1 Answer 1

1

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 ...")
answered Jan 7, 2015 at 16:24
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.