Re-evaluating a string?

John Machin sjmachin at lexicon.net
Mon Jul 24 06:20:17 EDT 2006


Tim Chase wrote:
[snip]
>  As
> such, I'd rework the move() function I suggested to simply be
> something like
>
> def move(rate,lo,hi,chan=1):
> 	return "!SC%c%c%c%c\r" % (chan, rate, lo, hi)
>
> where you possibly even just pass in the "position" parameter,
> and let the function do the splitting with something like
>
> def move(rate,position,chan=1)
> 	hi,lo = divmod(position & 0xFFFF, 256)
> 	return "!SC%c%c%c%c\r" % (chan, rate, lo, hi)
>
> or optionally use the struct module to unpack them.

Say what? We need to pack the position first, we can't use
struct.unpack on an integer, only a string. So that ends up looking
like this:

def move(rate,position,chan=1):
    lo, hi = struct.unpack("<BB", struct.pack("<H", position))
    return "!SC%c%c%c%c\r" % (chan, rate, lo, hi)

which is a bit, shall we say, unfortunate. Why unpack it when we've
already packed it just so we can pack it with another method? This is
getting close to dailyWTF territory. Forget that. Let's go the whole
hog with struct.pack:

def move(rate,position,chan=1):
    return struct.pack("<3sBBHs", "!SC", chan, rate, position, "\r")

What I tell you 3 times is true ... just use struct.pack and stop
faffing about. Get used to it. One day you'll have to output a negative
1-or-two-byte integer, a four-byte integer, a float even -- no
scratching your head about what bits to shift, what mask to use, just
fill in the codes from the manual and away you go.

HTH,
John



Cheers,
John




More information about the Python-list mailing list