[Tutor] creating a connection class

Steven D'Aprano steve at pearwood.info
Fri Mar 30 22:14:36 EDT 2018


On Fri, Mar 30, 2018 at 02:55:14PM +0000, Glenn Schultz wrote:
> All,
> 
> I can create a connection as follows and it works but I think it is best to 
> have a connection class that opens and closes.

You already have one: that's what pyodbc.connect is.

The documentation is pretty poor:

https://github.com/mkleehammer/pyodbc/wiki/Connection

but as far as I can tell, pyodbc is a helper function which chooses the 
correct class to instantiate depending on the database you connect 
to, and returns an instance of that class.

In Design Pattern terms, I think that counts as an Abstract Factory.

> I create the connection 
> class as outline below.  However, it does not work - meaning that it does 
> not return a connection rather it returns 
> <__main__.modelingdb at 0x40dfbb0>

When you call the class, you get back an instance of that class. That's 
exactly what you have there: an instance of your modelingdb class.


> class modelingdb(object):
>   def __init__(self):
>    self._db_connection = pyodbc.connect(
>    driver = '{ODBC Driver 13 for SQL Server}',
>    server = 'foo',
>    database = 'foo',
>    username = 'foo',
>    password = 'foo',
>    trusted_connection = 'yes')
>    self._db_cur = self._db_connection.cursor()
> 
> def __del__(self):
> self._db_connection.close()

The indentation on this is wrong, so that code won't work.

Also, you cannot rely on __del__ in Python classes. This is totally the 
wrong way to use this.

Can I guess that you're a Java or C++ programmer trying to learn Python? 
Wrapping the connection object in another object is not helpful: you're 
just duplicating (poorly) what's already been done.

If you are new to Python from a Java background, you might find some 
things take a bit of getting used to. These things may help:


Python is not Java.

http://dirtsimple.org/2004/12/python-is-not-java.html

And Java is not Python either.

http://dirtsimple.org/2004/12/java-is-not-python-either.html)

Classes are not the centre of the Python universe:

https://www.youtube.com/watch?v=o9pEzgHorH0

We try to use more functional and even procedural techniques, but don't 
worry, classes are still okay

http://lucumr.pocoo.org/2013/2/13/moar-classes/

its just the crazy-extreme attitude that *everything* must *always* be a 
class that we object to.

http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html


-- 
Steve


More information about the Tutor mailing list