views:

133

answers:

3

I have an instance of a Connection (required to DB API 2.0-compliant), but I don't have the module from which it was imported. The problem is that I am trying to use named parameters, but I don't know which paramstyle to use.

Since paramstyle is a module-level constant, I can't just ask the Connection. I tried using inspect.getmodule() on my Connection instance, but it just returned None. Is there an easier way that I'm just missing, or will I need to do some try/except code to determine which paramstyle to use?

Thanks.

+2  A: 

Where did you get the instance from? I can't imagine a situation where you won't know the beforehand the source of the connection. If the user of your library is passing you a connection, ask him for the paramstyle as well.

Anyway, look at the following console session:

>>> import sqlite3
>>> c = sqlite3.connect('/tmp/test.db')
>>> c
<sqlite3.Connection object at 0xb7db2320>
>>> type(c)
<type 'sqlite3.Connection'>
>>> type(c).__module__
'sqlite3'
>>> import sys
>>> sys.modules[type(c).__module__].paramstyle
'qmark'

However that sucks. I wouldn't rely on it not even for a second. I use my own connection-like objects, and I'd like to pass one of those to your library. I'd hate it when it tries to magically find out the paramstyle and fails because I am using a connection-like wrapper object.

nosklo
+1  A: 

Pass type(connection) (connection class) to inspect.getmodule(), not connection object. The class tracks the module it was defined in so inspect can find it, while object creation is not tracked.

Denis Otkidach
+2  A: 

You can't.

You can try by looking at connection.__class__.__module__, but it's not specified by DB-API that it'll work. In fact for many common cases it won't. (eg. the class is defined in a submodule of the package that acts as the DB-API module object; or the class is a C extension with no __module__.)

It is unfortunate, but you will have to pass a reference to the DB-API module object around with the DB-API connection object.

bobince