1. 程式人生 > >關於python模組迴圈匯入(circular imports)/相對匯入(Relative Imports)/絕對匯入(Absolute Imports)的官方資料

關於python模組迴圈匯入(circular imports)/相對匯入(Relative Imports)/絕對匯入(Absolute Imports)的官方資料

In Python 2.4 and earlier, if you're reading a module located inside a package, it is not clear whether

import foo

refers to a top-level module or to another module inside the package. As Python's library expands, more and more existing package internal modules suddenly shadow standard library modules by accident. It's a particularly difficult problem inside packages because there's no way to specify which module is meant. To resolve the ambiguity, it is proposed that foo

 will always be a module or package reachable from sys.path. This is called an absolute import.

The python-dev community chose absolute imports as the default because they're the more common use case and because absolute imports can provide all the functionality of relative (intra-package) imports -- albeit at the cost of difficulty when renaming package pieces higher up in the hierarchy or when moving one package inside another.

Because this represents a change in semantics, absolute imports will be optional in Python 2.5 and 2.6 through the use of

from __future__ import absolute_import

This part of the proposal had BDFL approval from the beginning.