0

I'm having an issue when trying to pass a sqlite query to another function.

The issue is that the sqlite query MAY contains a list and therefore I cannot use *args as it unpacks the tuple but then ignores the list, example query I'm attempting to pass to the function:

'SELECT postname FROM history WHERE postname = ? COLLATE NOCASE', [u'Test']

So in this case I could use args as opposed to *args in the destination function, however I may have a sqlite query that doesn't contain a list and therefore I can't always do this e.g.

'SELECT * FROM history' 

so I guess my question in a nutshell is how can I successfully pass a sqlite query to another function whether it contains a list or not, using args?

4

2 回答 2

1

你可以tryexcept

try:
   func(*args)
except TypeError:
   func(args)

当然,这也会TypeError在你的函数中捕获 s 。因此,您可能希望创建另一个实际处理解包的函数,并确保为您提供一个可解包的对象作为回报。这也不适用于字符串,因为它们也会解包(见评论)。

这是一个确保可以解包对象的函数。

def unpackable(obj):
    if hasattr(obj,'__iter__'):
       return obj
    else:
       return (obj,)

func(*unpackable(args))
于 2012-11-19T16:13:19.887 回答
1

我认为这里最好的答案是尝试并确保您始终放入可迭代的内容,而不是尝试处理拥有单个项目的奇怪情况。

如果你('SELECT postname FROM history WHERE postname = ? COLLATE NOCASE', [u'Test'])在一个地方,传递一个长度为 1 的元组更有意义 -('SELECT * FROM history', )而不是字符串。

您还没有说字符串的来源,因此您可能根本无法更改数据的方式,但如果可以,元组是从代码中删除边缘情况的更好选择。

如果你真的不能这样做,那么你想要的是解压缩任何非字符串迭代,检查可以按照这个问题所示完成。

于 2012-11-19T16:31:41.687 回答