[Tutor] dbus.Array to string

Steven D'Aprano steve at pearwood.info
Mon Aug 12 03:04:48 CEST 2013


On 12/08/13 08:53, Amit Saha wrote:
> Hello all,
>
> The other day, I had to convert a dbus.Array [1] object to a string. I
> found a way to do it, but I am not sure if that is the best way.


Does the Array object not have a "toString" method? Or similar?

What do you get when you call str() or repr() on the Array object?


> Here is a dbus.Array object:
>
> dbus.Array([dbus.Byte(66), dbus.Byte(105), dbus.Byte(103),
> dbus.Byte(80), dbus.Byte(111), dbus.Byte(110), dbus.Byte(100),
> dbus.Byte(54), dbus.Byte(55), dbus.Byte(57), dbus.Byte(68),
> dbus.Byte(56), dbus.Byte(53)], signature=dbus.Signature('y'),
> variant_level=1)


Basically it is an array of bytes, with a couple of extra arguments. Do you care about the signature and variant_level arguments?



> And this is how I converted it to it's string representation:

Careful. In usual Python terminology, the string representation of an object, or just repr, is the string that represents how the object is created, more or less. So the string representation would be something like:

"Array([Byte(66), Byte(105), ..., Byte(53)], signature=Signature('y'), variant_level=1)"

which is nothing like what you want.


>>>> import dbus
>
>>>> ssid = "dbus.Array([dbus.Byte(66), dbus.Byte(105), dbus.Byte(103), dbus.Byte(80), dbus.Byte(111), dbus.Byte(110), dbus.Byte(100), dbus.Byte(54), dbus.Byte(55), dbus.Byte(57), dbus.Byte(68), dbus.Byte(56), dbus.Byte(53)], signature=dbus.Signature('y'), variant_level=1)
> "

Here you create a string, which looks like "dbus.Array(...)".


>>>> ssid = ''.join([chr(character) for character in ssid])

Since ssid is already a string, iterating over it gives you characters; calling chr() on a character raises an exception.


>>>> ssid
> 'BigPond679D85'

Not with the code you provide.


If you drop the quotation marks around the dbus.Array, so you get an Array object instead of a string, then your code may work. But look at your list comprehension:

[chr(character) for character in ssid]

That's confusing. If iterating over ssid gives characters, as the code claims, then there is no need to call chr(), and in fact you wouldn't need the list comp at all, you could just say:

''.join(ssid)


But it isn't an array of characters, it is an array of bytes. So:

''.join([chr(byte) for byte in ssid])

is less misleading and confusing.

Another alternative:

''.join(map(chr, ssid))


is more terse, but may not be as readable to those who aren't familiar with map. Both forms should be more or less equally as efficient.



-- 
Steven


More information about the Tutor mailing list