Domanda

Quando si utilizza la comprensione dell'elenco o la parola chiave in in un contesto di ciclo for, ovvero:

for o in X:
    do_something_with(o)

o

l=[o for o in X]
  • Come funziona il meccanismo alla base di in?
  • Quali funzioni \ metodi all'interno di X chiama?
  • Se X può essere conforme a più di un metodo, qual è la precedenza?
  • Come scrivere un X efficiente, in modo che la comprensione dell'elenco sia rapida?
È stato utile?

Soluzione

La, afaik, risposta completa e corretta.

for, sia nei cicli for che nelle comprensioni di liste, chiama iter() su X. iter() restituirà un iterabile se X ha un metodo __iter__ o un metodo __getitem__. Se implementa entrambi, viene utilizzato __iter__. Se non ha nessuno dei due, ottieni TypeError: 'Nothing' object is not iterable.

Questo implementa un __getitem__:

class GetItem(object):
    def __init__(self, data):
        self.data = data

    def __getitem__(self, x):
        return self.data[x]

Utilizzo:

>>> data = range(10)
>>> print [x*x for x in GetItem(data)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Questo è un esempio di implementazione di __iter__:

class TheIterator(object):
    def __init__(self, data):
        self.data = data
        self.index = -1

    # Note: In  Python 3 this is called __next__
    def next(self):
        self.index += 1
        try:
            return self.data[self.index]
        except IndexError:
            raise StopIteration

    def __iter__(self):
        return self

class Iter(object):
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        return TheIterator(data)

Utilizzo:

>>> data = range(10)
>>> print [x*x for x in Iter(data)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Come vedi, hai bisogno sia di implementare un iteratore, sia di __iter__ che restituisca l'iteratore.

Puoi combinarli:

class CombinedIter(object):
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        self.index = -1
        return self

    def next(self):
        self.index += 1
        try:
            return self.data[self.index]
        except IndexError:
            raise StopIteration

Utilizzo:

>>> well, you get it, it's all the same...

Ma allora puoi avere un solo iteratore attivo alla volta. OK, in questo caso potresti semplicemente fare questo:

class CheatIter(object):
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        return iter(self.data)

Ma questo è un inganno perché stai solo riutilizzando il metodo __iter__ di list. Un modo più semplice è usare yield e trasformare __iter__ in un generatore:

class Generator(object):
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        for x in self.data:
            yield x

Quest'ultimo è il modo in cui lo consiglierei. Facile ed efficiente.

Altri suggerimenti

X deve essere iterabile.Deve implementare __iter__() che restituisce un oggetto iteratore;l'oggetto iteratore deve implementare next(), che restituisce l'elemento successivo ogni volta che viene chiamato o solleva un StopIteration se non c'è l'elemento successivo.

Liste, tuple e generatori sono tutti iterabili.

Nota che il semplice operatore for utilizza lo stesso meccanismo.

Answering question's comments I can say that reading source is not the best idea in this case. The code that is responsible for execution of compiled code (ceval.c) does not seem to be very verbose for a person that sees Python sources for the first time. Here is the snippet that represents iteration in for loops:

   TARGET(FOR_ITER)
        /* before: [iter]; after: [iter, iter()] *or* [] */
        v = TOP();

        /*
          Here tp_iternext corresponds to next() in Python
        */
        x = (*v->ob_type->tp_iternext)(v); 
        if (x != NULL) {
            PUSH(x);
            PREDICT(STORE_FAST);
            PREDICT(UNPACK_SEQUENCE);
            DISPATCH();
        }
        if (PyErr_Occurred()) {
            if (!PyErr_ExceptionMatches(
                            PyExc_StopIteration))
                break;
            PyErr_Clear();
        }
        /* iterator ended normally */
        x = v = POP();
        Py_DECREF(v);
        JUMPBY(oparg);
        DISPATCH();

To find what actually happens here you need to dive into bunch of other files which verbosity is not much better. Thus I think that in such cases documentation and sites like SO are the first place to go while the source should be checked only for uncovered implementation details.

X must be an iterable object, meaning it needs to have an __iter__() method.

So, to start a for..in loop, or a list comprehension, first X's __iter__() method is called to obtain an iterator object; then that object's next() method is called for each iteration until StopIteration is raised, at which point the iteration stops.

I'm not sure what your third question means, and how to provide a meaningful answer to your fourth question except that your iterator should not construct the entire list in memory at once.

Maybe this helps (tutorial http://docs.python.org/tutorial/classes.html Section 9.9):

Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method next() which accesses elements in the container one at a time. When there are no more elements, next() raises a StopIteration exception which tells the for loop to terminate.

To answer your questions:

How does the mechanism behind in works?

It is the exact same mechanism as used for ordinary for loops, as others have already noted.

Which functions\methods within X does it call?

As noted in a comment below, it calls iter(X) to get an iterator. If X has a method function __iter__() defined, this will be called to return an iterator; otherwise, if X defines __getitem__(), this will be called repeatedly to iterate over X. See the Python documentation for iter() here: http://docs.python.org/library/functions.html#iter

If X can comply to more than one method, what's the precedence?

I'm not sure what your question is here, exactly, but Python has standard rules for how it resolves method names, and they are followed here. Here is a discussion of this:

Method Resolution Order (MRO) in new style Python classes

How to write an efficient X, so that list comprehension will be quick?

I suggest you read up more on iterators and generators in Python. One easy way to make any class support iteration is to make a generator function for iter(). Here is a discussion of generators:

http://linuxgazette.net/100/pramode.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top