[PyKDE] QString -> python string via QString::latin1()

Phil Thompson phil at riverbankcomputing.co.uk
Thu Oct 6 22:31:36 BST 2005


On Thursday 06 October 2005 10:05 pm, Nigel Stewart wrote:
> Hi Phil,
>
> I certainly see what you mean, the counter-argument
> here is motivated from a pragmatic point of view -
> I don't want to be writing Python code to check
> the return type of every call to QString::latin1().
>
> >>Overall, a bug, or a feature?
> >
> > Feature.
> >
> >>I would certainly
> >>prefer that PyQt always returned a python string,
> >>treating QString::isNull() and QString::isEmpty()
> >>as the same case.
> >
> > Null and empty QStrings are different and the PyQt behaviour reflects the
> > Qt behaviour.
>
>     True, that's the QString convention.  I am not aware of
>     such a convention existing in Python for python strings.
>     It could be argued that the PyQt behaviour is escalating
>     a fine-grained QString semantic into a Python error-state:
>
> PyObject *PyString_FromString(const char *v)
>    Return value: New reference.
>    Returns a new string object with the value v
>    on success, and NULL on failure. The parameter
>    v must not be NULL; it will not be checked.
>
>     So a QString.latin1() returning NULL (which is not documented
>     as an error condition) is treated by PyQt as an error
>     condition, rather than converting into a zero-length Python
>     string.

No, it's not treating it as an error. It's just doing the usual mapping of 
NULL to None.

> >>I'm interested in the broader
> >>PyKde/PyQt opinion, is it "pythonic" to return
> >>different types of objects, depending on the
> >>input?
> >
> > str() is defined to return a string object. If there is a bug then it's
> > that str() of a null string should raise an exception. I'd be willing to
> > implement that for PyQt4

Given the point Jim made, I think the current behaviour is correct.

>      I think it would be preferable for the QString::isNull /
>      QString::isEmpty semantic to be ignored - if the python
>      side is interested in isNull/isEmpty it should be asking
>      the QString.
>
>      It seems to me quite a burden to need to check the return
>      type of every call to QString::latin1() via PyQt.  Raising
>      an exception would be even more cumbersome, from the point
>      of view of delivering robust python code.
>
> As it turns out, we can migrate to using str() or unicode()
> rather than latin1() - so I'm flagging this as an issue we
> came across, not something that affects our project adversly.

I think that's the right approach - convert using str/unicode asap and forget 
about QString or use QString with its full semantics - whichever suits you 
best.

Phil




More information about the PyQt mailing list