【发布时间】:2019-03-28 20:20:11
【问题描述】:
请注意,我问这个问题仅供参考
我知道标题听起来像是 Finding the source code for built-in Python functions? 的复制品。但是让我解释一下。
比如说我想找到collections.Counter类的most_common方法的源代码。由于Counter 类是在python 中实现的,我可以使用inspect 模块获取它的源代码。
即,
>>> import inspect
>>> import collections
>>> print(inspect.getsource(collections.Counter.most_common))
这将打印出来
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
所以如果方法或类在 C 中实现,inspect.getsource 将引发 TypeError。
>>> my_list = []
>>> print(inspect.getsource(my_list.append))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\abdul.niyas\AppData\Local\Programs\Python\Python36-32\lib\inspect.py", line 968, in getsource
lines, lnum = getsourcelines(object)
File "C:\Users\abdul.niyas\AppData\Local\Programs\Python\Python36-32\lib\inspect.py", line 955, in getsourcelines
lines, lnum = findsource(object)
File "C:\Users\abdul.niyas\AppData\Local\Programs\Python\Python36-32\lib\inspect.py", line 768, in findsource
file = getsourcefile(object)
File "C:\Users\abdul.niyas\AppData\Local\Programs\Python\Python36-32\lib\inspect.py", line 684, in getsourcefile
filename = getfile(object)
File "C:\Users\abdul.niyas\AppData\Local\Programs\Python\Python36-32\lib\inspect.py", line 666, in getfile
'function, traceback, frame, or code object'.format(object))
TypeError: <built-in method append of list object at 0x00D3A378> is not a module, class, method, function, traceback, frame, or code object.
所以我的问题是,有什么方法(或使用第三方包?)我们也可以找到用 C 实现的类或方法的源代码吗?
就是这样的
>> print(some_how_or_some_custom_package([].append))
int
PyList_Append(PyObject *op, PyObject *newitem)
{
if (PyList_Check(op) && (newitem != NULL))
return app1((PyListObject *)op, newitem);
PyErr_BadInternalCall();
return -1;
}
【问题讨论】:
-
我认为答案可能是否定的,除非您对 GitHub 进行某种抓取或反编译,因为您的本地计算机上可能根本不存在该源代码。 C 代码是在构建 python 发行版时编译的,您可能没有可用的 C 源文件。很想知道我错了,所以会留意这个问题。
标签: python-3.x cpython python-internals