Python defines two types of packages. regular packages and namespace packages. Regular packages are traditional packages as they existed in python3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package's namespace. The __init__.py file can contain the same python code that any other module can contain, and python will add some additional features to the module when it is imported.
python searches a list of directories to resolve names in e.g., import statements. Because these can be any direcotry, and arbitary ones can be added by the end user, the developers have to worry about directories that happen to share a name with a valid python module, such as string in the docs example. To alleviate this, it ignores directories which do not contain a file named __init__.py, even if it is blank.
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:
-
the directory containing the input script (or the current directory).
-
PYTHONPATH(a list of directory names, with the same syntax as the shell variablePATH). -
the installation-dependent default.
After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.
本文详细介绍了Python中两种类型的包:常规包和命名空间包。常规包作为目录包含__init__.py文件,当导入包时,此文件会被隐式执行。Python在导入模块时会搜索一系列目录,包括当前目录、PYTHONPATH环境变量指定的目录和安装依赖默认路径。文章还解释了如何通过修改sys.path来改变搜索路径。
478

被折叠的 条评论
为什么被折叠?



