我知道,这是错的,但有可能吗?
我认为当一个对象的.__iter__
方法返回迭代器时,它被认为是可迭代的?那么为什么这不起作用呢?
>>> from forbiddenfruit import curse
>>> def __iter__(self):
... for i in range(self):
... yield i
>>> curse(int, "__iter__", __iter__)
>>> for x in 5:
... print x
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
int
现在似乎有__iter__
方法:
>>> int(5).__iter__
<bound method int.__iter__ of 5>
答案 0 :(得分:6)
for
循环的反汇编是:
import dis
dis.dis("for _ in _: pass")
#>>> 1 0 SETUP_LOOP 14 (to 17)
#>>> 3 LOAD_NAME 0 (_)
#>>> 6 GET_ITER
#>>> >> 7 FOR_ITER 6 (to 16)
#>>> 10 STORE_NAME 0 (_)
#>>> 13 JUMP_ABSOLUTE 7
#>>> >> 16 POP_BLOCK
#>>> >> 17 LOAD_CONST 0 (None)
#>>> 20 RETURN_VALUE
所以我们想要GET_ITER
操作码。
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();
}
使用PyObject_GetIter
:
PyObject *
PyObject_GetIter(PyObject *o)
{
PyTypeObject *t = o->ob_type;
getiterfunc f = NULL;
f = t->tp_iter;
if (f == NULL) {
if (PySequence_Check(o))
return PySeqIter_New(o);
return type_error("'%.200s' object is not iterable", o);
}
else {
PyObject *res = (*f)(o);
if (res != NULL && !PyIter_Check(res)) {
PyErr_Format(PyExc_TypeError,
"iter() returned non-iterator "
"of type '%.100s'",
res->ob_type->tp_name);
Py_DECREF(res);
res = NULL;
}
return res;
}
}
首先检查t->tp_iter
是否为无效。
现在,这就是让所有内容点击的内容:
class X:
pass
X.__iter__ = lambda x: iter(range(10))
list(X())
#>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
from forbiddenfruit import curse
class X:
pass
curse(X, "__iter__", lambda x: iter(range(10)))
list(X())
#>>> Traceback (most recent call last):
#>>> File "", line 16, in <module>
#>>> TypeError: 'X' object is not iterable
当您在课堂上设置属性时,它会调用PyType_Type->setattro
:
static int
type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
{
if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
PyErr_Format(
PyExc_TypeError,
"can't set attributes of built-in/extension type '%s'",
type->tp_name);
return -1;
}
if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
return -1;
return update_slot(type, name);
}
请参阅update_slot
?这样就可以更新广告位,因此GET_ITER
的下一次调用将在tp->tp_iter
上点击X
。但是,forbiddenfruit
绕过了这个过程,只是在类中注入一个字典。这意味着PyLong_Type
保持默认值:
PyTypeObject PyLong_Type = {
...
0, /* tp_iter */
...
};
所以
if (f == NULL)
被触发,
if (PySequence_Check(o))
失败(因为它不是一个序列)然后它只是
return type_error("'%.200s' object is not iterable", o);