2013-03-21 10 views
12

Perché il seguente codice Python genera un errore
TypeError: type object argument after * must be a sequence, not generator
mentre se io commento la prima linea (inutile) generatore di f, tutto funziona bene?TypeError: tipo di argomento oggetto dopo * deve essere una sequenza, non generatore

from itertools import izip 

def z(): 
    for _ in range(10): 
     yield _ 

def f(z): 
    for _ in z: pass # if I comment this line it works! (??) 
    for x in range(10): 
     yield (x,10*x,100*x,1000*x) 

iterators = izip(*f(z)) 
for it in iterators: 
    print list(it) 

N.B. Quello che sto cercando di fare è, con un singolo generatore, restituire più iteratori (quanti ne passerò al generatore come argomenti). L'unico modo che ho trovato per farlo è di produrre tuple e usare izip() su di loro - magia nera per me.

+0

Si potrebbe trovare 'tee' da itertools interessanti ... – Tathagata

+0

' tee' deve correre attraverso e archiviare tutti gli elementi una volta prima di poter duplicare l'iteratore, cf. i documenti: https://docs.python.org/3.1/library/itertools.html#itertools.tee. Sfortunatamente non c'è magia, e il mio tentativo qui è stato ingenuo. – JulienD

risposta

26

Questo è divertente: si è dimenticato di chiamare z quando si passò a f:

iterators = izip(*f(z())) 

Così f cercato di iterare su un oggetto funzione:

for _ in z: pass # z is a function 

Ciò ha sollevato un TypeError:

TypeError: 'function' object is not iterable 

Interi di pitone catturati e controrilanciato con un messaggio di errore confuso.

# ceval.c 

static PyObject * 
ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk) 
{ 
... 

      t = PySequence_Tuple(stararg); 
      if (t == NULL) { 
       if (PyErr_ExceptionMatches(PyExc_TypeError)) { 
        PyErr_Format(PyExc_TypeError, 
           "%.200s%.200s argument after * " 
           "must be a sequence, not %200s", 
           PyEval_GetFuncName(func), 
           PyEval_GetFuncDesc(func), 
           stararg->ob_type->tp_name); 
... 
+4

Infatti, vedi http://bugs.python.org/issue4806 – georg

+0

Quattro anni, wow. –

+0

Oh grazie mille! – JulienD

Problemi correlati