How to convert a list/tuple into an function argument list easily?
Pierre Rouleau
pieroul at attglobal.net
Sun Dec 15 21:20:59 EST 2002
I was writing some code that uses the struct module to read and write
binary data. With it you can easily define the binary format of a file
record and read it into a binary string:
>>> import struct
>>> fn = 'c:/tmp/1.map'
>>> fd = open(fn,'rb')
>>> data = fd.read(8)
>>> data
'( \xa8\xc0r\x17\x03\x00'
>>> record = struct.unpack('<LHH',data)
>>> record
(3232243752L, 6002, 3)
So I end up with record, which is a tuple of 3 elements. Now if some
time later in the program, i want to write back the same information in
another file, the struct.pack() function helps you do that. But it will
not accept the tuple as its argument, you must supply each element
separately.
This fails:
>>> val = struct.pack('<LHH', record)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
struct.error: required argument is not an integer
But this works:
>>> val = struct.pack('<LHH', record[0], record[1], record[2])
>>>
Question:
=========
is there an easy way to convert a tuple into all of its elements so that
i could write something like:
val = struct.pack('<LHH', elementsOf(record))
Thanks!
--
Pierre
More information about the Python-list
mailing list