[PyKDE] Coerce QString to unicode or str?

Nigel Stewart ns at fluent.com
Fri Oct 7 17:42:01 BST 2005


PyQt happily converts python strings and unicode strings
into QString arguments for Qt API calls.  That's very
convenient.

In Python, string and unicode objects can be mixed,
and are coerced as needed:

 >> print type("hello" + unicode("world"))
<type 'unicode'>
 >> print type(unicode("hello") + "world")
<type 'unicode'>

What would be nice, would be similar handling for
QString:

 >> print type("hello" + qt.QString("world"))
Exception: cannot concatenate 'str' and 'qt.QString' objects
 >> print type(unicode("hello") + qt.QString("world"))
Exception: coercing to Unicode: need string or buffer, qt.QString found

Python provides 2.4 provides coersion for numeric
types, but is deprecated.  The intention is that
methods should explicitly deal with whatever type
of argument is given, rather than depend on coersion.

     "This section used to document the rules for coercion.
      ... In Python 3.0, coercion will not be supported."

http://www.python.org/doc/2.4.2/ref/coercion-rules.html

That raises two questions - (1) would it be desirable for
Python to quietly convert QStrings to unicode as needed,
and (2) is it technically possible in Python 2.4, 3.x?

A sip-based solution might be to provide SIP_PYUNICODE or
SIP_PYSTRING as alternative return types to QString.
But, I think it might be disruptive for the PyQt bindings
to be taken in this direction...

Regards,

Nigel Stewart




More information about the PyQt mailing list