_functools 模块
这个导入是怎么工作的,它用的是哪个文件呢?
import _functools
在Python 2.5中:
import _functools
print _functools.__file__
结果是:
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object has no attribute '__file__'
如果我看不懂C语言代码,怎么才能理解partial(从_functools导入partial)的意思呢?
5 个回答
这是一个共享对象 _functools.so
,是用C语言写的。我猜这个对象是由实际的 functools
模块引入的。你为什么要直接从它里面导入呢?当然可以这样做,不过你也可以直接用 from functools import partial
来导入。
对于Python2.6,_functools
模块是内置的。你可以在解释器提示符下输入import _functools ; repr(_functools)
并按回车,就能看到它。
如果你想查看这个模块的C语言源代码,可以访问http://hg.python.org/cpython/file/d7e85ddb1336/Modules/_functoolsmodule.c。
这个_functools
模块没有__file__
属性(见下一段),因为它是编译进了解释器里的。
对于Python2.5,_functools
模块是一个用C语言实现的标准库模块。如果你想查看它,可以访问http://hg.python.org/cpython/file/a78381ead4cf/Modules/_functoolsmodule.c。你可以通过在解释器提示符下输入import _functools ; print _functools.__file__
来查看这个模块是从哪里加载的。
C语言编写的模块可以是内置的(没有__file__
)或者存在于一个.so
或.pyd
的动态库中(这时它们的__file__
会显示出来)——这些都是实现细节,你不需要太在意。
如果你想通过研究代码来理解一个可以被Python调用的C语言函数是怎么工作的,学习如何阅读 C语言代码通常是最好的选择(这比实际用C语言编程要简单得多;-)。不过,你常常会找到一些“示例Python实现”,这些是C语言功能的非正式参考,你可以研究这些。
一个特别有用的资源是pypy
项目,它提供了用Python编写的标准库功能的等价实现,这些功能通常是用C语言编写的——你可以在这里浏览它的源代码pypy,当然你也可以下载到你的电脑上查看。
特别地,这是pypy的_functools.py实现:
""" Supplies the internal functions for functools.py in the standard library """
class partial:
"""
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
"""
__slots__ = ['func', 'args', 'keywords']
def __init__(self, func, *args, **keywords):
if not callable(func):
raise TypeError("the first argument must be callable")
self.func = func
self.args = args
self.keywords = keywords
def __call__(self, *fargs, **fkeywords):
newkeywords = self.keywords.copy()
newkeywords.update(fkeywords)
return self.func(*(self.args + fargs), **newkeywords)
希望这段代码读起来和理解起来都很简单!