今天翻到Python-China.org的这个帖子用__all__暴露接口,觉得还挺有意思的,专门下了Python的源码看__all__的姿势。
源代码里Python/import.c的函数static ini ensure_fromlist里面可以看到和__all__有关的逻辑:
if (PyString_AS_STRING(item)[0] == '*') { /* 如果import *这样 */ PyObject *all; Py_DECREF(item); /* See if the package defines __all__ */ if (recursive) continue; /* Avoid endless recursion */ all = PyObject_GetAttrString(mod, "__all__"); if (all == NULL) PyErr_Clear(); else { int ret = ensure_fromlist(mod, all, buf, buflen, 1); Py_DECREF(all); if (!ret) return 0; } continue;}
其中除了ensure_fromlist递归之外,最主要的就是PyObject_GetAttrString。可以看出,如果是import *的话就会读__all__字段,然后最主要的方法是PyObject_GetAttrString,到后面是个递归了。我们可以看PyObject_GetAttrString这个方法。在Objects/object.c里面。去掉无用代码,实际上就走到PyObject_GetAttr这个方法了。
去掉一些增减计数器的方法,直接就能看到返回的结果代码:
if (tp->tp_getattro != NULL) return (*tp->tp_getattro)(v, name);if (tp->tp_getattr != NULL) return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
然后就是这个地方。tp可以看作是某个类型吧,代码如下。
PyTypeObject *tp = Py_TYPE(v);
Py_TYPE在Include/object.h里。
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
所以tp可以当成比如string,就是PyBaseString_Type之类的。每个类型都有tp_getattro或tp_getattr方法,就看如何实现。所以看上去其实list或者tuple都可以,因为各自有自己重载的getattr,这么说,string也行吧?
__all__ = 'ab'def a(): print 'this is a'def b(): print 'this is b'def c(): print 'this is c'
可以import *
试试看,a、b都可以,c是不行的。
那么如果这么写:
__all__ = 'ab'def a(): print 'this is a'def b(): print 'this is b'def ab(): print 'this is ab'def c(): print 'this is c'
那么import *
可以使用ab吗?答案是不行的。这就要看上面的tp_getattro代码了。这个代码在Objects/stringobject.c里。我们可以看到tp->tp_getattro就是PyObject_GenericGetAttr。那么dig这个代码,就能知道为什么ab不行了。其实从逻辑上来想,Python的string类型想象成字符的数组也很好理解。
当然这个纯属好玩,锻炼一下自己看Python代码的能力。开发中不应该import *
,更不应该乱把__all__写成str。
代码基于Python2.7.x,也许其中理解也不一定对。