Pack array of namedtuples in PYTHON
Question: I need to send an array of namedtuples by a socket.

To create the array of namedtuples I use de following:

    
    
    listaPeers=[]
    for i in range(200):
         ipPuerto=collections.namedtuple('ipPuerto', 'ip, puerto')
         ipPuerto.ip="121.231.334.22"
         ipPuerto.puerto="8988"
         listaPeers.append(ipPuerto)
    

Now that is filled, i need to pack "listaPeers[200]"

How can i do it?

Something like?:

    
    
    packedData = struct.pack('XXXX',listaPeers)
    


Answer: First of all you are using namedtuple incorrectly. It should look something
like this:

    
    
     # ipPuerto is a type
     ipPuerto=collections.namedtuple('ipPuerto', 'ip, puerto')
    
     # theTuple is a tuple object
     theTuple = ipPuerto("121.231.334.22", "8988")
    

As for packing, it depends what you want to use on the other end. If the data
will be read by Python, you can just use Pickle module.

    
    
    import cPickle as Pickle
    pickledTuple = Pickle.dumps(theTuple)
    

You can pickle whole array of them at once.

