常规和命名空间包的sys.path导入顺序

2024-06-17 12:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

正如官方文件所说:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path.

它将在sys.path中从第一个包搜索到最后一个包

但我遇到一个例子不符合这一点

以下是一个例子:

当我安装了烧瓶时:

>>> import flask
>>> flask.__path__
['/home/yixuan/.local/lib/python3.6/site-packages/flask']

如果我在我的自定义目录(即/home/yixuan/temp)下创建一个dirflask,那么我运行以下命令:

>>> import sys
>>> sys.path
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/yixuan/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> sys.path.insert(0, '/home/yixuan/temp')
>>> sys.path
['/home/yixuan/temp', '', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/yixuan/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> import flask
>>> flask.__path__
['/home/yixuan/.local/lib/python3.6/site-packages/flask']

(这是两个独立的口译员会话!)

我不知道为什么烧瓶包装不是我的定制烧瓶目录。在sys.path/home/yixuan/.local/lib/python3.6/site-packages放在/home/yixuan/temp之后,根据我的理解,这是不正常的,不是吗?如果是,是什么原因导致这种情况发生


Tags: pathimportflaskhome烧瓶libpackagesusr
2条回答

没有__init__.pyflask/)文件的目录是命名空间包,而不是常规包(flask/__init__.py)或模块(flask.py)。虽然名称空间包是按sys.path的顺序记录的,但它们仅在没有找到任何常规包或模块时使用


PEP 420 Implicit Namespace Packages

...

Specification

...

While looking for a module or package named "foo", for each directory in the parent path:

  • If <directory>/foo/__init__.py is found, a regular package is imported and returned.
  • If not, but <directory>/foo.{py,pyc,so,pyd} is found, a module is imported and returned. The exact list of extension varies by platform and whether the -> O flag is specified. The list here is representative.
  • If not, but <directory>/foo is found and is a directory, it is recorded and the scan continues with the next directory in the parent path.
  • Otherwise the scan continues with the next directory in the parent path.

If the scan completes without returning a module or package, and at least one directory was recorded, then a namespace package is created.

...

sys.path documentation关于进口的说明。Flask现在是python 3安装的一部分

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations.

相关问题 更多 >