问题描述
我从没注意到在今天之前在某些软件包上定义的__path__
属性.根据文档:
I had never noticed the __path__
attribute that gets defined on some of my packages before today. According to the documentation:
虽然此功能并不常见 需要时,可以用来扩展 包中找到的一组模块.
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/src/myproject/lib/python2.6/site-packages/zope/schema
中更本地地使用了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
类似,但更了解路径上的压缩.
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__
进行猴子补丁,例如,有时我会通过创建文件distutils/__init__.py
来创建猴子补丁distutils,而该文件早于sys.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__有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!