当我只有一个“Connection”对象时,如何确定正确的“paramstyle”?
我有一个 Connection
实例(符合 DB API 2.0 要求),但我没有从中导入它的模块。问题是我正在尝试使用命名参数,但我不知道要使用哪个 paramstyle
。
由于 paramstyle
是模块级常量,我不能只询问 Connection
。我尝试使用 inspect.getmodule()
在我的 Connection
实例上,但它只返回 None
。有没有我缺少的更简单的方法,或者我需要执行一些 try
/except
代码来确定要使用哪个 paramstyle
?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
type(connection)
(连接类)传递给inspect.getmodule()
,而不是连接对象。该类跟踪定义它的模块,以便inspect
可以找到它,但不跟踪对象创建。Pass
type(connection)
(connection class) toinspect.getmodule()
, not connection object. The class tracks the module it was defined in soinspect
can find it, while object creation is not tracked.您从哪里获取实例?我无法想象您事先不知道连接来源的情况。如果您的库的用户向您传递连接,也请向他询问 paramstyle。
不管怎样,看看下面的控制台会话:
然而这很糟糕。我一秒钟都不会依赖它。我使用自己的类似连接的对象,并且我想将其中之一传递到您的库。当它试图神奇地找出 paramstyle 并失败时,我会讨厌它,因为我使用的是类似连接的包装对象。
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:
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.
你不能。
您可以尝试查看
connection.__class__.__module__
,但 DB-API 并未指定它可以工作。事实上,对于许多常见情况,它不会。(例如,该类在充当 DB-API 模块对象的包的子模块中定义;或者该类是没有__module__< 的 C 扩展/code>.)
不幸的是,您必须使用 DB-API 连接对象传递对 DB-API 模块对象的引用。
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.