How can printing an object result in different out

2020-07-02 10:26发布

I was testing some code on the interpreter and I noticed some unexpected behavior for the sqlite3.Row class.

My understanding was that print obj will always get the same result as print str(obj), and typing obj into the interpreter will get the same result as print repr(obj), however this is not the case for 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>

I think sqlite3.Row must be a subclass of tuple, but I still don't understand exactly what is going on behind the scenes that could cause this behavior. Can anyone explain this?

This was tested on Python 2.5.1, not sure if the behavior is the same for other Python versions.

Not sure whether or not this matters, but the row_factory attribute for my Connection was set to sqlite3.Row.

标签: python sqlite
2条回答
Juvenile、少年°
2楼-- · 2020-07-02 11:10

PySqlite provides the special native hook for print, but it doesn't implement __repr__ or __str__. I'd say that's a bit of a missed chance, but at least it explains the behavior you're observing.

See pysqlite source: https://github.com/ghaering/pysqlite/blob/master/src/row.c#L241 And python docs: http://docs.python.org/c-api/typeobj.html#tp_print

查看更多
一夜七次
3楼-- · 2020-07-02 11:21
s = str(tuple(row))

is a workaround if you want the original tuple string representation.

It is useful for example if you want to log the row easily as in:

logging.debug(tuple(user_row))

Works because rows are iterable.

查看更多
登录 后发表回答