Created
October 6, 2014 12:46
-
-
Save asvetlov/fd3930dad4bfca431cc3 to your computer and use it in GitHub Desktop.
For loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In [1]: import dis | |
In [2]: for i in range(10): | |
...: print(i) | |
...: | |
0 | |
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
In [3]: def f(): | |
...: for i in range(10): | |
...: print(i) | |
...: | |
In [4]: dis.dis(f) | |
2 0 SETUP_LOOP 30 (to 33) | |
3 LOAD_GLOBAL 0 (range) | |
6 LOAD_CONST 1 (10) | |
9 CALL_FUNCTION 1 (1 positional, 0 keyword pair) | |
12 GET_ITER | |
>> 13 FOR_ITER 16 (to 32) | |
16 STORE_FAST 0 (i) | |
3 19 LOAD_GLOBAL 1 (print) | |
22 LOAD_FAST 0 (i) | |
25 CALL_FUNCTION 1 (1 positional, 0 keyword pair) | |
28 POP_TOP | |
29 JUMP_ABSOLUTE 13 | |
>> 32 POP_BLOCK | |
>> 33 LOAD_CONST 0 (None) | |
36 RETURN_VALUE | |
-------------------------------------------------------------------- | |
./Python/ceval.c, GET_ITER/FOR_ITER implementation: | |
TARGET(GET_ITER) { | |
/* before: [obj]; after [getiter(obj)] */ | |
PyObject *iterable = TOP(); | |
PyObject *iter = PyObject_GetIter(iterable); | |
Py_DECREF(iterable); | |
SET_TOP(iter); | |
if (iter == NULL) | |
goto error; | |
PREDICT(FOR_ITER); | |
DISPATCH(); | |
} | |
PREDICTED_WITH_ARG(FOR_ITER); | |
TARGET(FOR_ITER) { | |
/* before: [iter]; after: [iter, iter()] *or* [] */ | |
PyObject *iter = TOP(); | |
PyObject *next = (*iter->ob_type->tp_iternext)(iter); | |
if (next != NULL) { | |
PUSH(next); | |
PREDICT(STORE_FAST); | |
PREDICT(UNPACK_SEQUENCE); | |
DISPATCH(); | |
} | |
if (PyErr_Occurred()) { | |
if (!PyErr_ExceptionMatches(PyExc_StopIteration)) | |
goto error; | |
else if (tstate->c_tracefunc != NULL) | |
call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f); | |
PyErr_Clear(); | |
} | |
/* iterator ended normally */ | |
STACKADJ(-1); | |
Py_DECREF(iter); | |
JUMPBY(oparg); | |
DISPATCH(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment