Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can printing an object result in different output than both str() and repr()?

Tags:

python

sqlite

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.

like image 394
Andrew Clark Avatar asked Oct 27 '11 18:10

Andrew Clark


1 Answers

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

like image 174
Ondergetekende Avatar answered Sep 30 '22 22:09

Ondergetekende