I've got a script with several functions that desire to make database calls. I am looking to get better at writing clean code as opposed to just tossing together scripts with horrible style. What's generally considered the easiest method to begin a global database connection that may be utilized any place in the script however is not prone to errors for example accidentally changing the variable holding an association. I'd imagine I ought to be putting my way through a module? Any links to actual code could be very helpful too. Thanks.

If you're dealing with Python and databases, you can't afford to not look at SQLAlchemy:

SQLAlchemy may be the Python SQL toolkit and Object Relational Mapper that gives application designers the entire energy and versatility of SQL.

It possesses a full suite of well-known enterprise-level persistence designs, created for efficient and high-carrying out database access, modified right into a easy and Pythonic domain language.

I've built very complex databases having a remarkably little bit of code (a couple of hundred lines). The schema definition is nearly self-recording, the objects employed for the item Relational Mapper are Common Python Objects (i.e., what you have), and also the querying API is nearly apparent. Additionally, the documentation is great: many online good examples, fully recorded API, as well as an O'Reilly book which, while not even close to perfect, takes you against zero to harmful inside a couple of nights.

If you won't want to make use of the Object Relational Mapper, you could fall to plain connections and literal SQL. Also, the code is portable and database independent (exactly the same code works with MySQL, Oracle, SQLite, along with other database managers).

The Session object will instantly take proper care of the pooling (that which you mention as the concern).

The easiest method to understand its energy is most likely to follow along with the lessons acquired within the first result page from the Google query sqlalchemy tutorial.

Make use of a model system/ORM system.