2011-10-27 20 views
17

我正在测试解释器上的一些代码,我注意到一些sqlite3.Row类的意外行为。如何打印一个对象导致不同的输出比str()和repr()?

我的理解是print obj总是会得到相同的结果print str(obj),并键入obj到解释会得到相同的结果print repr(obj),但是这不是sqlite3.Row情况:

>>> print row  # the row object prints like a tuple 
(u'string',) 
>>> print str(row) # why wouldn't this match the output from above? 
<sqlite3.Row object at 0xa19a450> 

>>> row    # usually this would be the repr for an object 
(u'string',) 
>>> print repr(row) # but repr(row) is something different as well! 
<sqlite3.Row object at 0xa19a450> 

我想sqlite3.Row必须是tuple的子类,但我仍然不确切了解可能导致此行为的幕后操作。任何人都可以解释吗?

这是在Python 2.5.1上测试的,不确定其他Python版本的行为是否相同。

不确定这是否重要,但我的Connectionrow_factory属性设置为sqlite3.Row

+0

发布之前,你看过http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python吗? – ktdrv

+0

@kaloyan - 我找不到任何回答我的问题的东西,如果你能指点我的话。 –

+0

有趣的行为。 'sqlite3.Row'似乎不是子类的元组,所以我的猜测是print语句的特例列表和/或基于除继承之外的其他标准的元组,但是我在文档中找不到任何可以承认的东西,更不用说解释了。 – millimoose

回答

11

PySqlite为print提供了特殊的原生挂钩,但它没有实现__repr____str__。我会说这是一个错过的机会,但至少它解释了你正在观察的行为。

见pysqlite来源:https://github.com/ghaering/pysqlite/blob/master/src/row.c#L241 和Python文档:http://docs.python.org/c-api/typeobj.html#tp_print

+2

不错的发现!看来,sqlite开发人员反对这可能是为什么这在更多地方没有看到的建议。从文档:“类型永远不应该实现tp_print产生不同的输出比tp_repr或tp_str会”和“建议不要定义tp_print,而是依赖于tp_repr和tp_str打印”。 –

+3

我已经在pysqlite的错误跟踪器中链接了这个主题:http://code.google.com/p/pysqlite/issues/detail?id=4 – Ondergetekende

+0

@Ondergetekende错误链接被破坏,它是否在别的地方结束,或者我们会打开一个新的(在http://bugs.python.org/?) –

0
s = str(tuple(row)) 

是一个解决办法,如果你想在原来的元组字符串表示。

,如果你想轻松地登录该行作为它是有用的,例如:

logging.debug(tuple(user_row)) 

工作,因为行是可迭代。

相关问题