python dbus: dealing with strings

Neal H. Walfield neal at walfield.org
Wed Sep 7 01:04:05 PDT 2011


Hi,

I have written a Python module that wraps a service exposed via DBus.
When invoking the service, the wrapper first coerces the arguments to
the types expected by the DBus interface.  For instance:

  def foo(a, b, c):
    return iface.foo(dbus.UTF8String(a), dbus.Int32(b), dbus.Boolean(c)

I've found that dbus.UTF8String sometimes fails if its argument is a
unicode string that contains non-ascii characters (also: dbus.String
fails if its argument is a normal string that contains non-ascii
characters).  Consider:

  >>> import dbus
  >>> dbus.UTF8String(u'ä')
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in
  position 0: ordinal not in range(128)
  >>> dbus.UTF8String('ä')
  dbus.UTF8String('\xc3\xa4')

(The string contains the letter a with an umlaut.)

This is a bit curious: dbus.UTF8String doesn't accept a properly
encoded unicode string!  Further, the other dbus conversion functions
appear to do their best to convert the argument to the right type.
Consider:

  >>> dbus.Int32("3")
  dbus.Int32(3)


In my particular case, I want to avoid burdening the client with
having to do casts itself by, say, only accepting UTF8 strings: the
data is coming from the web via feedparser.

Should I rewrite my code as follows:

  def foo(a, b, c):
    return iface.foo(a if isinstance(a, unicode) else dbus.UTF8String(a),
                     dbus.Int32(b), dbus.Boolean(c)

That's ugly.

Help is appreciated.

Thanks,

Neal

    


More information about the dbus mailing list