Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how generators work in python

I am novice in Python and programming. Generators are a bit too complicated to understand for new programmers. Here's my theory on generator functions in Python:

  1. Any function contains a yield statement will return a generator object

  2. A generator object is a stack contains state

  3. Each time I call .next method Python extracts the function's state and when it finds another yield statement it'll bind the state again and deletes the prior state:

Example:

 [ 
  [state1] # Stack contains states and states contain info about the function
  [state2] # State1 will be deleted when python finds the other yield? 
 ] 

This is of course might be like the stupidest theory on earth, but forgive me I am just new in the coding word.

My Questions:

  1. What Python internally makes to store the states ?

  2. Does yield statement adds a state to a stack if it exists ?

  3. What yield creates internally ? I understand yield creates a generator object, however, I wonder what generator objects contain that makes them work ? are they just a stack/list of states and we you use .next method to extract each state and Python will call the function with the indexed state automatically for instance ?

like image 959
user3786562 Avatar asked Aug 10 '14 19:08

user3786562


People also ask

What is generator function in Python with example?

The following is a simple generator function. Example: Generator Function. def mygenerator(): print('First item') yield 10 print('Second item') yield 20 print('Last item') yield 30. In the above example, the mygenerator() function is a generator function. It uses yield instead of return keyword.

Why do we use generators in Python?

Generators have been an important part of Python ever since they were introduced with PEP 255. Generator functions allow you to declare a function that behaves like an iterator. They allow programmers to make an iterator in a fast, easy, and clean way.

How does a generator work internally?

The modern-day generator works on the principle of electromagnetic induction discovered by Michael Faraday in 1831-32. Faraday discovered that the above flow of electric charges could be induced by moving an electrical conductor, such as a wire that contains electric charges, in a magnetic field.

How does Python yield work?

The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.


1 Answers

Any function contains a yield statement will return a generator object

This is correct. The return value of a function containing a yield is a generator object. The generator object is an iterator, where each iteration returns a value that was yielded from the code backing the generator.

A generator object is a stack contains state

A generator object contains a pointer to a the current execution frame, along with a whole bunch of other stuff used to maintain the state of the generator. The execution frame is what contains the call stack for the code in the generator.

Each time I call .next method Python extracts the function's state and when it finds another yield statement it'll bind the state again and deletes the prior state

Sort of. When you call next(gen_object), Python evaluates the current execution frame:

gen_send_ex(PyGenObject *gen, PyObject *arg, int exc) {  // This is called when you call next(gen_object)
    PyFrameObject *f = gen->gi_frame;
    ...
    gen->gi_running = 1;
    result = PyEval_EvalFrameEx(f, exc);  // This evaluates the current frame
    gen->gi_running = 0; 

PyEval_EvalFrame is highest-level function used to interpret Python bytecode:

PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)

This is the main, unvarnished function of Python interpretation. It is literally 2000 lines long. The code object associated with the execution frame f is executed, interpreting bytecode and executing calls as needed. The additional throwflag parameter can mostly be ignored - if true, then it causes an exception to immediately be thrown; this is used for the throw() methods of generator objects.

It knows that when it hits a yield while evaluating the bytecode, it should return the value being yielded to the caller:

    TARGET(YIELD_VALUE) {
        retval = POP();
        f->f_stacktop = stack_pointer;
        why = WHY_YIELD;
        goto fast_yield;
    }

When you yield, the current value of the frame's value stack is maintained (via f->f_stacktop = stack_pointer), so that we can resume where we left off when next is called again. All non-generator functions set f_stacktop to NULL after they're done evaluating. So when you call next again on the generator object, PyEval_ExvalFrameEx is called again, using the same frame pointer as before. The pointer's state will be exactly the same as it was when it yielded during the previous, so execution will continue on from that point. Essentially the current state of the frame is "frozen". This is described in the PEP that introduced generators:

If a yield statement is encountered, the state of the function is frozen, and the value [yielded] is returned to .next()'s caller. By "frozen" we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time .next() is invoked, the function can proceed exactly as if the yield statement were just another external call.

Here is most of the state a generator object maintains (taken directly from its header file):

typedef struct {
    PyObject_HEAD
    /* The gi_ prefix is intended to remind of generator-iterator. */

    /* Note: gi_frame can be NULL if the generator is "finished" */
    struct _frame *gi_frame;

    /* True if generator is being executed. */
    char gi_running;

    /* The code object backing the generator */
    PyObject *gi_code;

    /* List of weak reference. */
    PyObject *gi_weakreflist;

    /* Name of the generator. */
    PyObject *gi_name;

    /* Qualified name of the generator. */
    PyObject *gi_qualname;
} PyGenObject;

gi_frame is the pointer to the current execution frame.

Note that all of this is CPython implementation-specific. PyPy/Jython/etc. could very well be implementing generators in a completely different way. I encourage you to read through the source for generator objects to learn more about CPython's implementation.

like image 78
dano Avatar answered Oct 23 '22 19:10

dano