Вопрос

При использовании понимания списка или ключевого слова in в контексте цикла for, например:

родовое слово

или

родовое слово
  • Как работает механизм генерирования кода кода?
  • Какие функции \ методы в коде in он вызывает?
  • Если X может соответствовать нескольким методам, каков их приоритет?
  • Как написать эффективный генерирующий код кода, чтобы понимание списка было быстрым?
Это было полезно?

Решение

Ага, полный и правильный ответ.

for, как в циклах for, так и при составлении списков, вызывает iter() для X. iter() вернет итерацию, если X имеет либо метод __iter__, либо метод __getitem__. Если он реализует и то, и другое, используется код генерирующего кода. Если нет ни того, ни другого, вы получите код сгенерированного кода.

Это реализует общий код кода:

родовое слово

Использование:

родовое слово

Это пример реализации кода __iter__:

родовое слово

Использование:

родовое слово

Как видите, вам нужно реализовать итератор, и создать код кода, который возвращает итератор.

Их можно комбинировать:

родовое слово

Использование:

родовое слово

Но тогда у вас может быть только один итератор одновременно. Хорошо, в этом случае вы можете просто сделать это:

родовое слово

Но это обман, потому что вы просто повторно используете метод TypeError: 'Nothing' object is not iterable для __getitem__. Более простой способ - использовать yield и превратить код __iter__ в генератор:

родовое слово

Я бы порекомендовал последний вариант. Легко и эффективно.

Другие советы

X должен быть повторяемым.Он должен реализовывать __iter__(), который возвращает объект-итератор;объект-итератор должен реализовывать next(), который возвращает следующий элемент каждый раз, когда он вызывается, или вызывает код StopIteration, если следующего элемента нет.

Списки, кортежи и генераторы можно повторять.

Обратите внимание, что простой оператор for использует тот же механизм.

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top