How do I determine the correct `paramstyle` when all I have is a" Connection "object?
I have an instance Connection
(required for DB API 2.0 compatibility), but I do not have the module from which it was imported. The problem is I am trying to use named parameters, but I don't know which one to paramstyle
use.
Since this paramstyle
is a module level constant, I can't just ask Connection
. I tried using inspect.getmodule()
on my instance Connection
, but it just returned None
. Is there an easier way I'm just missing, or would I have to do some code try
/ except
to figure out which one to paramstyle
use?
source to share
Where did you get your copy? I cannot imagine a situation where you will not know in advance the source of the connection. If the user of your library passes you a connection, ask them for paramstyle too.
Anyway, take a 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, it sucks. I would not count on it for a second. I am using my own plug-in-like objects and I would like to pass one of them to your library. I hate it when it magically tries to find out the paramstyle and fails because I am using a join-like wrapper object.
source to share
You can not.
You can try by looking connection.__class__.__module__
, but it is not specified by the DB-API that it will work. In fact, for many common cases, this will not be the case. (for example, a class is defined in a submodule of a package that acts as a DB-API module object, or the class is an extension of C without __module__
.)
Unfortunately, you will need to pass a reference to the DB-API module object around the DB-API connection object.
source to share