问题描述
在今天之前,我从未注意到在我的一些包上定义的 __path__
属性.根据文档:
I had never noticed the __path__
attribute that gets defined on some of my packages before today. According to the documentation:
包支持另一种特殊的属性,__path__
.这是初始化为一个包含保存目录的名称包的 __init__.py
在代码之前在该文件中执行.这变量可以修改;这样做影响未来对模块的搜索和包含在包.
虽然这个功能并不常见需要,它可以用来扩展在包中找到的一组模块.
While this feature is not often needed, it can be used to extend the set of modules found in a package.
有人可以向我解释一下这到底意味着什么以及我为什么想要使用它吗?
Could somebody explain to me what exactly this means and why I would ever want to use it?
推荐答案
这通常与 pkgutil 一起使用 让一个包在磁盘上布局.例如,zope.interface 和 zope.schema 是独立的发行版(zope
是一个命名空间包").您可能在 /usr/lib/python2.6/site-packages/zope/interface/
中安装了 zope.interface,而您在 /home/me 中更本地地使用了 zope.schema/src/myproject/lib/python2.6/site-packages/zope/schema
.
This is usually used with pkgutil to let a package be laid out across the disk. E.g., zope.interface and zope.schema are separate distributions (zope
is a "namespace package"). You might have zope.interface installed in /usr/lib/python2.6/site-packages/zope/interface/
, while you are using zope.schema more locally in /home/me/src/myproject/lib/python2.6/site-packages/zope/schema
.
如果你把 pkgutil.extend_path(__path__, __name__)
放在 /usr/lib/python2.6/site-packages/zope/__init__.py
中,那么两个 zope.interface 和 zope.schema 将是可导入的,因为 pkgutil 会将 __path__
更改为 ['/usr/lib/python2.6/site-packages/zope', '/home/me/src/myproject/lib/python2.6/site-packages/zope']
.
If you put pkgutil.extend_path(__path__, __name__)
in /usr/lib/python2.6/site-packages/zope/__init__.py
then both zope.interface and zope.schema will be importable because pkgutil will have change __path__
to ['/usr/lib/python2.6/site-packages/zope', '/home/me/src/myproject/lib/python2.6/site-packages/zope']
.
pkg_resources.declare_namespace
(Setuptools 的一部分)类似于 pkgutil.extend_path
但更了解路径上的 zips.
pkg_resources.declare_namespace
(part of Setuptools) is like pkgutil.extend_path
but is more aware of zips on the path.
手动更改 __path__
并不常见,也可能没有必要,尽管在调试命名空间包的导入问题时查看变量很有用.
Manually changing __path__
is uncommon and probably not necessary, though it is useful to look at the variable when debugging import problems with namespace packages.
您也可以使用 __path__
进行猴子修补,例如,我有时通过在 sys 上创建一个文件
:distutils/__init__.py
来对 distutils 进行猴子修补.path
You can also use __path__
for monkeypatching, e.g., I have monkeypatched distutils at times by creating a file distutils/__init__.py
that is early on sys.path
:
import os
stdlib_dir = os.path.dirname(os.__file__)
real_distutils_path = os.path.join(stdlib_dir, 'distutils')
__path__.append(real_distutils_path)
execfile(os.path.join(real_distutils_path, '__init__.py'))
# and then apply some monkeypatching here...
这篇关于__path__ 有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!