struct: type registration?

Giovanni Bajo raNOsky at deveSPAMler.com
Thu Jun 1 13:44:40 EDT 2006


John Machin wrote:

>> Looks like you totally misread my message.
>
> Not at all.
>
> Your function:
>
> def mystring_pack(s):
>      if len(s) > 20:
>          raise ValueError, "a mystring can be at max 20 chars"
>      s = (s + "\0"*20)[:20]
>      s = struct.pack("20s", s)
>      return s
>
> can be even better replaced by (after reading the manual "For packing,
> the string is truncated or padded with null bytes as appropriate to
> make it fit.") by:
>
> def mystring_pack(s):
>      if len(s) > 20:
>          raise ValueError, "a mystring can be at max 20 chars"
>      return s
>      # return s = (s + "\0"*20)[:20] # not needed, according to the
>      manual # s = struct.pack("20s", s)
>      # As I said, this particular instance of using struct.pack is a
> big fat no-op.

John, the point of the example was to show that one could write custom
packer/unpacker which calls struct.pack/unpack and, after that,
post-processes the results to obtain some custom data type. Now, I apologize
if my example wasn't exactly the shortest, most compact, most pythonic piece
of code. It was not meant to be. It was meant to be very easy to read and
very clear in what it is being done. You are nitpicking that part of my code
is a no-op. Fine. Sorry if this confused you. I was just trying to show a
simple pattern:

custom packer: adjust data, call struct.pack(), return
custom unpacker: call struct.unpack(), adjust data, return

I should have chosen a most complex example probably, but I did not want to
confuse readers. It seems I have confused them by choosing too simple an
example.
-- 
Giovanni Bajo





More information about the Python-list mailing list