[Python] ¿Qué significa la palabra clave "rendimiento"?


Answers

Grokking directo al yield Grokking

Cuando vea una función con declaraciones de yield , aplique este sencillo truco para comprender lo que sucederá:

  1. Inserte un result = [] línea result = [] al comienzo de la función.
  2. Reemplace cada yield expr con result.append(expr) .
  3. Inserte un return result línea en la parte inferior de la función.
  4. Yay, ¡no más declaraciones de yield ! Lee y descubre el código.
  5. Compare la función con la definición original.

Este truco puede darle una idea de la lógica detrás de la función, pero lo que realmente ocurre con el yield es significativamente diferente de lo que sucede en el enfoque basado en listas. En muchos casos, el enfoque de rendimiento será mucho más eficiente en la memoria y más rápido también. En otros casos, este truco te atrapará en un ciclo infinito, a pesar de que la función original funciona bien. Sigue leyendo para saber más ...

No confunda sus Iterables, Iteradores y Generadores

Primero, el protocolo de iterador : cuando escribes

for x in mylist:
    ...loop body...

Python realiza los dos pasos siguientes:

  1. Obtiene un iterador para mylist :

    Call iter(mylist) -> esto devuelve un objeto con un método next() (o __next__() en Python 3).

    [Este es el paso del que la mayoría de la gente se olvida decírtelo]

  2. Utiliza el iterador para recorrer los elementos:

    Siga llamando al método next() en el iterador devuelto desde el paso 1. El valor de retorno de next() se asigna a x y se ejecuta el cuerpo del bucle. Si se StopIteration una excepción StopIteration desde next() , significa que no hay más valores en el iterador y se sale del ciclo.

La verdad es que Python realiza los dos pasos anteriores en cualquier momento que quiera recorrer el contenido de un objeto, por lo que podría ser un ciclo for, pero también podría ser un código como otherlist.extend(mylist) (donde otherlist es una lista de Python) .

Aquí mylist es iterable porque implementa el protocolo de iterador. En una clase definida por el usuario, puede implementar el __iter__() para que las instancias de su clase sean iterables. Este método debería devolver un iterador . Un iterador es un objeto con un método next() . Es posible implementar tanto __iter__() como next() en la misma clase, y tener __iter__() return self . Esto funcionará para casos simples, pero no cuando desee que dos iteradores recorran el mismo objeto al mismo tiempo.

Entonces ese es el protocolo iterador, muchos objetos implementan este protocolo:

  1. Listas integradas, diccionarios, tuplas, conjuntos, archivos.
  2. Clases definidas por el usuario que implementan __iter__() .
  3. Generadores.

Tenga en cuenta que un bucle for no sabe con qué tipo de objeto está tratando, simplemente sigue el protocolo del iterador y se complace en obtener el artículo tras el next() . Las listas incorporadas devuelven sus artículos uno por uno, los diccionarios devuelven las claves una por una, los archivos devuelven las líneas una por una, etc. Y los generadores vuelven ... bueno, ahí es donde entra el yield :

def f123():
    yield 1
    yield 2
    yield 3

for item in f123():
    print item

En lugar de sentencias de yield , si tuviera tres declaraciones de return en f123() solo la primera se ejecutaría, y la función se cerraría. Pero f123() no es una función ordinaria. Cuando se llama a f123() , ¡ no devuelve ninguno de los valores en las declaraciones de rendimiento! Devuelve un objeto generador. Además, la función realmente no sale: entra en estado suspendido. Cuando el bucle for intenta recorrer el objeto del generador, la función se reanuda desde su estado suspendido en la siguiente línea después del yield que regresó anteriormente, ejecuta la siguiente línea de código, en este caso, una declaración de yield , y la devuelve como el siguiente artículo. Esto ocurre hasta que la función StopIteration , momento en el que el generador genera StopIteration y el ciclo sale.

Entonces, el objeto generador es algo así como un adaptador, en un extremo exhibe el protocolo del iterador, al exponer los __iter__() y next() para mantener el bucle for feliz. En el otro extremo, sin embargo, ejecuta la función lo suficiente para obtener el siguiente valor y lo pone nuevamente en modo suspendido.

¿Por qué usar generadores?

Usualmente puede escribir código que no usa generadores pero implementa la misma lógica. Una opción es usar la lista temporal 'truco' que mencioné antes. Eso no funcionará en todos los casos, por ejemplo, si tiene bucles infinitos, o puede hacer un uso ineficiente de la memoria cuando tiene una lista realmente larga. El otro enfoque es implementar una nueva clase iterable SomethingIter que mantiene el estado en los miembros de la instancia y realiza el siguiente paso lógico en su next() método next() (o __next__() en Python 3). Dependiendo de la lógica, el código dentro del método next() puede terminar pareciendo muy complejo y propenso a errores. Aquí los generadores proporcionan una solución limpia y fácil.

Question

¿Cuál es el uso de la palabra clave yield en Python? ¿Qué hace?

Por ejemplo, estoy tratando de entender este código 1 :

def _get_child_candidates(self, distance, min_dist, max_dist):
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild  

Y esta es la persona que llama:

result, candidates = [], [self]
while candidates:
    node = candidates.pop()
    distance = node._get_dist(obj)
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result

¿Qué sucede cuando se llama al método _get_child_candidates ? ¿Se devuelve una lista? Un solo elemento? Se llama nuevamente? ¿Cuándo se detendrán las llamadas subsiguientes?

1. El código proviene de Jochen Schulz (jrschulz), quien hizo una gran biblioteca de Python para espacios métricos. Este es el enlace a la fuente completa: Módulo mspace .




From a programming viewpoint, the iterators are implemented as thunks

http://en.wikipedia.org/wiki/Thunk_(functional_programming)

To implement iterators/generators/thread pools for concurrent execution/etc as thunks (also called anonymous functions), one uses messages sent to a closure object, which has a dispatcher, and the dispatcher answers to "messages".

http://en.wikipedia.org/wiki/Message_passing

" next " is a message sent to a closure, created by " iter " call.

There are lots of ways to implement this computation. I used mutation but it is easy to do it without mutation, by returning the current value and the next yielder.

Here is a demonstration which uses the structure of R6RS but the semantics is absolutely identical as in python, it's the same model of computation, only a change in syntax is required to rewrite it in python.

Welcome to Racket v6.5.0.3.

-> (define gen
     (lambda (l)
       (define yield
         (lambda ()
           (if (null? l)
               'END
               (let ((v (car l)))
                 (set! l (cdr l))
                 v))))
       (lambda(m)
         (case m
           ('yield (yield))
           ('init  (lambda (data)
                     (set! l data)
                     'OK))))))
-> (define stream (gen '(1 2 3)))
-> (stream 'yield)
1
-> (stream 'yield)
2
-> (stream 'yield)
3
-> (stream 'yield)
'END
-> ((stream 'init) '(a b))
'OK
-> (stream 'yield)
'a
-> (stream 'yield)
'b
-> (stream 'yield)
'END
-> (stream 'yield)
'END
-> 



TL;DR

When you find yourself building a list from scratch...

def squares_list(n):
    the_list = []                         # Replace
    for x in range(n):
        y = x * x
        the_list.append(y)                # these
    return the_list                       # lines

... yield each piece instead

def squares_the_yield_way(n):
    for x in range(n):
        y = x * x
        yield y                           # with this

This was my first "aha" moment with yield.

yield is a sugary way to say

build a series of stuff

Same behavior:

>>> for square in squares_list(4):
...     print(square)
...
0
1
4
9
>>> for square in squares_the_yield_way(4):
...     print(square)
...
0
1
4
9

Different behavior:

Yield is single-pass : you can only iterate through once. When a function has a yield in it we call it a generator function . And an iterator is what it returns. That's revealing. We lose the convenience of a container, but gain the power of an arbitrarily long series.

Yield is lazy , it puts off computation. A function with a yield in it doesn't actually execute at all when you call it. The iterator object it returns uses magic to maintain the function's internal context. Each time you call next() on the iterator (this happens in a for-loop) execution inches forward to the next yield. ( return raises StopIteration and ends the series.)

Yield is versatile . It can do infinite loops:

>>> def squares_all_of_them():
...     x = 0
...     while True:
...         yield x * x
...         x += 1
...
>>> squares = squares_all_of_them()
>>> for _ in range(4):
...     print(next(squares))
...
0
1
4
9

If you need multiple passes and the series isn't too long, just call list() on it:

>>> list(squares_the_yield_way(4))
[0, 1, 4, 9]

Brilliant choice of the word yield because both meanings apply:

yield — produce or provide (as in agriculture)

...provide the next data in the series.

yield — give way or relinquish (as in political power)

...relinquish CPU execution until the iterator advances.




Many people use return rather than yield but in some cases yield can be more efficient and easier to work with.

Here is an example which yield is definitely best for:

return (in function)

import random

def return_dates():
    dates = [] # with return you need to create a list then return it
    for i in range(5):
        date = random.choice(["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"])
        dates.append(date)
    return dates

yield (in function)

def yield_dates():
    for i in range(5):
        date = random.choice(["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"])
        yield date # yield makes a generator automatically which works in a similar way, this is much more efficient

Calling functions

dates_list = return_dates()
print(dates_list)
for i in dates_list:
    print(i)

dates_generator = yield_dates()
print(dates_generator)
for i in  dates_generator:
    print(i)

Both functions do the same thing but yield uses 3 lines instead of 5 and has one less variable to worry about.

This is the result from the code:

As you can see both functions do the same thing, the only difference is return_dates() gives a list and yield_dates() gives a generator

A real life example would be something like reading a file line by line or if you just want to make a generator




Yield is an Object

A return in a function will return a single value.

If you want function to return huge set of values use yield .

More importantly, yield is a barrier

like Barrier in Cuda Language, it will not transfer control until it gets completed.

es decir

It will run the code in your function from the beginning until it hits yield . Then, it'll return the first value of the loop. Then, every other call will run the loop you have written in the function one more time, returning the next value until there is no value to return.




(My below answer only speaks from the perspective of using Python generator, not the underlying implementation of generator mechanism , which involves some tricks of stack and heap manipulation.)

When yield is used instead of a return in a python function, that function is turned into something special called generator function . That function will return an object of generator type. The yield keyword is a flag to notify the python compiler to treat such function specially. Normal functions will terminate once some value is returned from it. But with the help of the compiler, the generator function can be thought of as resumable. That is, the execution context will be restored and the execution will continue from last run. Until you explicitly call return, which will raise a StopIteration exception (which is also part of the iterator protocol), or reach the end of the function. I found a lot of references about generator but this one from the functional programming perspective is the most digestable.

(Now I want to talk about the rationale behind generator , and the iterator based on my own understanding. I hope this can help you grasp the essential motivation of iterator and generator. Such concept shows up in other languages as well such as C#.)

As I understand, when we want to process a bunch of data, we usually first store the data somewhere and then process it one by one. But this intuitive approach is problematic. If the data volume is huge, it's expensive to store them as a whole beforehand. So instead of storing the data itself directly, why not store some kind of metadata indirectly, ie the logic how the data is computed .

There are 2 approaches to wrap such metadata.

  1. The OO approach, we wrap the metadata as a class . This is the so-called iterator who implements the iterator protocol (ie the __next__() , and __iter__() methods). This is also the commonly seen iterator design pattern .
  2. The functional approach, we wrap the metadata as a function . This is the so-called generator function . But under the hood, the returned generator object still IS-A iterator because it also implements the iterator protocol.

Either way, an iterator is created, ie some object that can give you the data you want. The OO approach may be a bit complex. Anyway, which one to use is up to you.




La palabra clave yield se reduce a dos simples hechos:

  1. Si el compilador detecta la palabra clave yield cualquier lugar dentro de una función, esa función ya no regresa a través de la declaración return . En cambio , devuelve inmediatamente un objeto perezoso de "lista pendiente" llamado generador
  2. Un generador es iterable. ¿Qué es un iterable ? Es como una list o set o range o dict-view, con un protocolo incorporado para visitar cada elemento en un orden determinado .

En pocas palabras: un generador es una lista floja, progresivamente pendiente , y las declaraciones de yield permiten usar la notación de función para programar los valores de lista que el generador debe escupir incrementalmente.

generator = myYieldingFunction(...)
x = list(generator)

   generator
       v
[x[0], ..., ???]

         generator
             v
[x[0], x[1], ..., ???]

               generator
                   v
[x[0], x[1], x[2], ..., ???]

                       StopIteration exception
[x[0], x[1], x[2]]     done

list==[x[0], x[1], x[2]]

Ejemplo

Definamos una función makeRange que sea como el range de Python. Llamar a makeRange(n) DEVOLUCIONES DE UN GENERADOR:

def makeRange(n):
    # return 0,1,2,...,n-1
    i = 0
    while i < n:
        yield i
        i += 1

>>> makeRange(5)
<generator object makeRange at 0x19e4aa0>

Para forzar al generador a que devuelva inmediatamente sus valores pendientes, puede pasarlo a list() (como cualquier iterable):

>>> list(makeRange(5))
[0, 1, 2, 3, 4]

Comparando el ejemplo con "solo devolver una lista"

El ejemplo anterior puede considerarse simplemente como crear una lista a la que anexas y regresas:

# list-version                   #  # generator-version
def makeRange(n):                #  def makeRange(n):
    """return [0,1,2,...,n-1]""" #~     """return 0,1,2,...,n-1"""
    TO_RETURN = []               #>
    i = 0                        #      i = 0
    while i < n:                 #      while i < n:
        TO_RETURN += [i]         #~         yield i
        i += 1                   #          i += 1  ## indented
    return TO_RETURN             #>

>>> makeRange(5)
[0, 1, 2, 3, 4]

Sin embargo, hay una gran diferencia; ver la última sección.

Cómo puedes usar generadores

Un iterable es la última parte de una lista de comprensión, y todos los generadores son iterables, por lo que a menudo se usan de esta manera:

#                   _ITERABLE_
>>> [x+10 for x in makeRange(5)]
[10, 11, 12, 13, 14]

Para tener una mejor idea de los generadores, puede jugar con el módulo itertools (asegúrese de usar chain.from_iterable vez de chain cuando lo justifique). Por ejemplo, incluso podría usar generadores para implementar listas perezosas infinitamente largas como itertools.count() . Usted podría implementar su propio def enumerate(iterable): zip(count(), iterable) , o alternativamente hacerlo con la palabra clave yield en un while-loop.

Tenga en cuenta: los generadores se pueden usar para muchas cosas más, como la implementación de corutinas o programación no determinista u otras cosas elegantes. Sin embargo, el punto de vista de "listas diferidas" que presento aquí es el uso más común que encontrarás.

Entre bastidores

Así es como funciona el "protocolo de iteración de Python". Es decir, qué está sucediendo cuando haces una list(makeRange(5)) . Esto es lo que describo anteriormente como una "lista incremental y perezosa".

>>> x=iter(range(5))
>>> next(x)
0
>>> next(x)
1
>>> next(x)
2
>>> next(x)
3
>>> next(x)
4
>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

La función incorporada next() solo llama a la función de objetos .next() , que es parte del "protocolo de iteración" y se encuentra en todos los iteradores. Puedes usar manualmente la función next() (y otras partes del protocolo de iteración) para implementar cosas sofisticadas, generalmente a expensas de la legibilidad, así que trata de evitar hacer eso ...

Minucias

Normalmente, a la mayoría de las personas no les importarían las siguientes distinciones y probablemente quieran dejar de leer aquí.

En Python-speak, un iterable es cualquier objeto que "entiende el concepto de un for-loop" como una lista [1,2,3] , y un iterador es una instancia específica del for-loop requerido como [1,2,3].__iter__() . Un generador es exactamente igual que cualquier iterador, excepto por la forma en que fue escrito (con la sintaxis de la función).

Cuando solicita un iterador de una lista, crea un nuevo iterador. Sin embargo, cuando solicita un iterador de un iterador (que rara vez haría), simplemente le da una copia de sí mismo.

Por lo tanto, en el improbable caso de que no puedas hacer algo como esto ...

> x = myRange(5)
> list(x)
[0, 1, 2, 3, 4]
> list(x)
[]

... entonces recuerda que un generador es un iterador ; es decir, es de uso único. Si desea reutilizarlo, debe llamar a myRange(...) nuevamente. Si necesita usar el resultado dos veces, convierta el resultado a una lista y guárdelo en una variable x = list(myRange(5)) . Aquellos que necesitan absolutamente clonar un generador (por ejemplo, que están haciendo una metaprogramación terriblemente hackosa) pueden usar itertools.tee si es absolutamente necesario, ya que la propuesta de estándares PyEP del iterador copiable ha sido diferida.




For those who prefer a minimal working example, meditate on this interactive Python session:

>>> def f():
...   yield 1
...   yield 2
...   yield 3
... 
>>> g = f()
>>> for i in g:
...   print i
... 
1
2
3
>>> for i in g:
...   print i
... 
>>> # Note that this time nothing was printed



I was going to post "read page 19 of Beazley's 'Python: Essential Reference' for a quick description of generators", but so many others have posted good descriptions already.

Also, note that yield can be used in coroutines as the dual of their use in generator functions. Although it isn't the same use as your code snippet, (yield) can be used as an expression in a function. When a caller sends a value to the method using the send() method, then the coroutine will execute until the next (yield) statement is encountered.

Generators and coroutines are a cool way to set up data-flow type applications. I thought it would be worthwhile knowing about the other use of the yield statement in functions.




yield is just like return - it returns whatever you tell it to. The only difference is that the next time you call the function, execution starts from the last call to the yield statement.

In the case of your code, the function get_child_candidates is acting like an iterator so that when you extend your list, it adds one element at a time to the new list.

list.extend calls an iterator until it's exhausted. In the case of the code sample you posted, it would be much clearer to just return a tuple and append that to the list.




Here is a mental image of what yield does.

I like to think of a thread as having a stack (even when it's not implemented that way).

When a normal function is called, it puts its local variables on the stack, does some computation, then clears the stack and returns. The values of its local variables are never seen again.

With a yield function, when its code begins to run (ie after the function is called, returning a generator object, whose next() method is then invoked), it similarly puts its local variables onto the stack and computes for a while. But then, when it hits the yield statement, before clearing its part of the stack and returning, it takes a snapshot of its local variables and stores them in the generator object. It also writes down the place where it's currently up to in its code (ie the particular yield statement).

So it's a kind of a frozen function that the generator is hanging onto.

When next() is called subsequently, it retrieves the function's belongings onto the stack and re-animates it. The function continues to compute from where it left off, oblivious to the fact that it had just spent an eternity in cold storage.

Compare the following examples:

def normalFunction():
    return
    if False:
        pass

def yielderFunction():
    return
    if False:
        yield 12

When we call the second function, it behaves very differently to the first. The yield statement might be unreachable, but if it's present anywhere, it changes the nature of what we're dealing with.

>>> yielderFunction()
<generator object yielderFunction at 0x07742D28>

Calling yielderFunction() doesn't run its code, but makes a generator out of the code. (Maybe it's a good idea to name such things with the yielder prefix for readability.)

>>> gen = yielderFunction()
>>> dir(gen)
['__class__',
 ...
 '__iter__',    #Returns gen itself, to make it work uniformly with containers
 ...            #when given to a for loop. (Containers return an iterator instead.)
 'close',
 'gi_code',
 'gi_frame',
 'gi_running',
 'next',        #The method that runs the function's body.
 'send',
 'throw']

The gi_code and gi_frame fields are where the frozen state is stored. Exploring them with dir(..) , we can confirm that our mental model above is credible.




It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as C#'s iterator blocks if you're familiar with those.

There's an IBM article which explains it reasonably well (for Python) as far as I can see.

The key idea is that the compiler/interpreter/whatever does some trickery so that as far as the caller is concerned, they can keep calling next() and it will keep returning values - as if the generator method was paused . Now obviously you can't really "pause" a method, so the compiler builds a state machine for you to remember where you currently are and what the local variables etc look like. This is much easier than writing an iterator yourself.




All great answers whereas a bit difficult for newbies.

I assume you have learned return statement.
As an analogy, return and yield are twins.
return means 'Return and Stop' whereas 'yield` means 'Return but Continue'

  1. Try to get a num_list with return .
def num_list(n):
    for i in range(n):
        return i

Ejecutarlo:

In [5]: num_list(3)
Out[5]: 0

See, you get only a single number instead of a list of them,. return never allow you happy to prevail. It implemented once and quit.

  1. There comes yield

Replace return with yield

In [10]: def num_list(n):
    ...:     for i in range(n):
    ...:         yield i
    ...:

In [11]: num_list(3)
Out[11]: <generator object num_list at 0x10327c990> 

In [12]: list(num_list(3))
Out[12]: [0, 1, 2]

Now, you win to get all the numbers.
Comparing to return which runs once and stops, yield runs times you planed.
You can interpret return as return one of them ,
yield as return all of them . This is called iterable .

  1. One more step we can rewrite yield statement with return
In [15]: def num_list(n):
    ...:     result = []
    ...:     for i in range(n):
    ...:         result.append(i)
    ...:     return result

In [16]: num_list(3)
Out[16]: [0, 1, 2]

It's the core about yield .

The difference between a list return outputs and the object yield output is:
You can get [0, 1, 2] from a list object always whereas can only retrieve them from 'the object yield output' once.
So, it has a new name generator object as displayed in Out[11]: <generator object num_list at 0x10327c990> .

In conclusion as a metaphor to grok it,

return and yield are twins,
list and generator are twins.




Yet another TL;DR

iterator on list : next() returns the next element of the list

iterator generator : next() will compute the next element on the fly (execute code)

You can see the yield/generator as a way to manually run the control flow from outside (like continue loop 1 step), by calling next, however complex the flow.

NOTE: the generator is NOT a normal function, it remembers previous state like local variables (stack), see other answers or articles for detailed explanation, the generator can only be iterated on once . You could do without yield but it would not be as nice, so it can be considered 'very nice' language sugar.




While a lot of answers show why you'd use a yield to create a generator, there are more uses for yield . It's quite easy to make a coroutine, which enables the passing of information between two blocks of code. I won't repeat any of the fine examples that have already been given about using yield to create a generator.

To help understand what a yield does in the following code, you can use your finger to trace the cycle through any code that has a yield . Every time your finger hits the yield , you have to wait for a next or a send to be entered. When a next is called, you trace through the code until you hit the yield … the code on the right of the yield is evaluated and returned to the caller… then you wait. When next is called again, you perform another loop through the code. However, you'll note that in a coroutine, yield can also be used with a send … which will send a value from the caller into the yielding function. If a send is given, then yield receives the value sent, and spits it out the left hand side… then the trace through the code progresses until you hit the yield again (returning the value at the end, as if next was called).

Por ejemplo:

>>> def coroutine():
...     i = -1
...     while True:
...         i += 1
...         val = (yield i)
...         print("Received %s" % val)
...
>>> sequence = coroutine()
>>> sequence.next()
0
>>> sequence.next()
Received None
1
>>> sequence.send('hello')
Received hello
2
>>> sequence.close()





Links