If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you've written in several programs without copying its definition into each program.
如果你退出 Python 解釋器重新進(jìn)入,以前創(chuàng)建的一切定義(變量和函數(shù))就全部丟失了。因此,如果你想寫(xiě)一些長(zhǎng)久保存的程序,最好使用一個(gè)文本編輯器來(lái)編寫(xiě)程序,把保存好的文件輸入解釋器。我們稱之為創(chuàng)建一個(gè)腳本。程序變得更長(zhǎng)一些了,你可能為了方便維護(hù)而把它分離成幾個(gè)文件。你也可能想要在幾個(gè)程序中都使用一個(gè)常用的函數(shù),但是不想把它的定義復(fù)制到每一個(gè)程序里。
To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
為了滿足這些需要,Python提供了一個(gè)方法可以從文件中獲取定義,在腳本或者解釋器的一個(gè)交互式實(shí)例中使用。這樣的文件被稱為模塊;模塊中的定義可以導(dǎo)入到另一個(gè)模塊或主模塊中(在腳本執(zhí)行時(shí)可以調(diào)用的變量集位于最高級(jí),并且處于計(jì)算器模式)
A module is a file containing Python definitions and statements. The
file name is the module name with the suffix .py appended. Within
a module, the module's name (as a string) is available as the value of
the global variable __name__
. For instance, use your favorite text
editor to create a file called fibo.py in the current directory
with the following contents:
模塊是包 括Python 定義和聲明的文件。文件名就是模塊名加上 .py 后綴。模塊的模塊名(做為一個(gè)字符串)可以由全局變量 __name__
得到。例如,你可以用自己慣用的文件編輯器在當(dāng)前目錄下創(chuàng)建一個(gè)叫 fibo.py 的文件,錄入如下內(nèi)容:
# Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result
Now enter the Python interpreter and import this module with the following command:
現(xiàn)在進(jìn)入Python解釋器,用如下命令導(dǎo)入這個(gè)模塊:
>>> import fibo
This does not enter the names of the functions defined in fibo
directly in the current symbol table; it only enters the module name
fibo
there.
Using the module name you can access the functions:
這樣做不會(huì)直接把 fibo
中的函數(shù)導(dǎo)入當(dāng)前的語(yǔ)義表;它只是引入了模塊名 fibo
。你可以通過(guò)模塊名按如下方式訪問(wèn)這個(gè)函數(shù):
>>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> fibo.__name__ 'fibo'
If you intend to use a function often you can assign it to a local name:
如果你想要直接調(diào)用函數(shù),通?梢越o它賦一個(gè)本地名稱:
>>> fib = fibo.fib >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module is imported somewhere.6.1
模塊可以像函數(shù)定義一樣包含執(zhí)行語(yǔ)句。這些語(yǔ)句通常用于初始化模塊。它們只在模塊第一次導(dǎo)入時(shí)執(zhí)行一次。6.2
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user's global variables.
對(duì)應(yīng)于定義模塊中所有函數(shù)的全局語(yǔ)義表,每一個(gè)模塊有自己的私有語(yǔ)義表。因此,模塊作者可以在模塊中使用一些全局變量,不會(huì)因?yàn)榕c用戶的全局變量沖突而引發(fā)錯(cuò)誤。
On the other hand, if you know what you are doing you can touch a
module's global variables with the same notation used to refer to its
functions,
modname.itemname
.
另一方面,如果你確定你需要這個(gè),可以像引用模塊中的函數(shù)一樣獲取模塊中的全局變量,形如:modname.itemname
。
Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module's global symbol table.
模塊可以導(dǎo)入(import)其它模塊。習(xí)慣上所有的 import語(yǔ)句都放在模塊(或腳本,等等)的開(kāi)頭,但這并不是必須的。被導(dǎo)入的模塊名入在本模塊的全局語(yǔ)義表中。
There is a variant of the import statement that imports names from a module directly into the importing module's symbol table. For example:
import 語(yǔ)句的一個(gè)變體直接從被導(dǎo)入的模塊中導(dǎo)入命名到本模塊的語(yǔ)義表中。例如:
>>> from fibo import fib, fib2 >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken
in the local symbol table (so in the example, fibo
is not
defined).
這樣不會(huì)從局域語(yǔ)義表中導(dǎo)入模塊名(如上所示, fibo
沒(méi)有定義)。
There is even a variant to import all names that a module defines:
這樣可以導(dǎo)入所有除了以下劃線(_
)開(kāi)頭的命名。
>>> from fibo import * >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore
(_
).
這樣可以導(dǎo)入所有除了以下劃線(_
)開(kāi)頭的命名。
When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python.
導(dǎo)入一個(gè)叫 spam 的模塊時(shí),解釋器先在當(dāng)前目錄中搜索名為 spam.py 的文件,然后在環(huán)境變量 PYTHONPATH 表示的目錄列表中搜索,然后是環(huán)境變量 PATH 中的路徑列表。如果 PYTHONPATH 沒(méi)有設(shè)置,或者文件沒(méi)有找到,接下來(lái)搜索安裝目錄,在 Unix中,通常是 .:/usr/local/lib/python。
Actually, modules are searched in the list of directories given by the
variable sys.path
which is initialized from the directory
containing the input script (or the current directory),
PYTHONPATH and the installation-dependent default. This allows
Python programs that know what they're doing to modify or replace the
module search path. Note that because the directory containing the
script being run is on the search path, it is important that the
script not have the same name as a standard module, or Python will
attempt to load the script as a module when that module is imported.
This will generally be an error. See section
實(shí)際上,解釋器由 sys.path
變量指定的路徑目錄搜索模塊,該變量初始化時(shí)默認(rèn)包含了輸入腳本(或者當(dāng)前目錄),PYTHONPATH 和安裝目錄。這樣就允許Python程序(原文如此,programs;我猜想應(yīng)該是“programer”,程序員--譯者)了解如何修改或替換模塊搜索目錄。需要注意的是由于這些目錄中包含有搜索路徑中運(yùn)行的腳本,所以這些腳本不應(yīng)該和標(biāo)準(zhǔn)模塊重名,否則在導(dǎo)入模塊時(shí)Python會(huì)嘗試把這些腳本當(dāng)作模塊來(lái)加載。這通常會(huì)引發(fā)一個(gè)錯(cuò)誤。請(qǐng)參見(jiàn)6.2節(jié)“標(biāo)準(zhǔn)模塊(
As an important speed-up of the start-up time for short programs that use a lot of standard modules, if a file called spam.pyc exists in the directory where spam.py is found, this is assumed to contain an already-``byte-compiled'' version of the module spam. The modification time of the version of spam.py used to create spam.pyc is recorded in spam.pyc, and the .pyc file is ignored if these don't match.
對(duì)于引用了大量標(biāo)準(zhǔn)模塊的短程序,有一個(gè)提高啟動(dòng)速度的重要方法,如果在 spam.py 所在的目錄下存在一個(gè)名為 spam.pyc 的文件,它會(huì)被視為 spam 模塊的預(yù)“編譯”(``byte-compiled'' ,二進(jìn)制編譯)版本。用于創(chuàng)建 spam.pyc 的這一版 spam.py 的修改時(shí)間記錄在 spam.pyc 文件中,如果兩者不匹配,.pyc 文件就被忽略。
Normally, you don't need to do anything to create the spam.pyc file. Whenever spam.py is successfully compiled, an attempt is made to write the compiled version to spam.pyc. It is not an error if this attempt fails; if for any reason the file is not written completely, the resulting spam.pyc file will be recognized as invalid and thus ignored later. The contents of the spam.pyc file are platform independent, so a Python module directory can be shared by machines of different architectures.
通常你不需要為創(chuàng)建 spam.pyc 文件做任何工作。一旦 spam.py 成功編譯,就會(huì)試圖編譯對(duì)應(yīng)版本的 spam.pyc。如果有任何原因?qū)е聦?xiě)入不成功,返回的 spam.pyc 文件就會(huì)視為無(wú)效,隨后即被忽略。 spam.pyc 文件的內(nèi)容是平臺(tái)獨(dú)立的,所以Python模塊目錄可以在不同架構(gòu)的機(jī)器之間共享。
Some tips for experts:
部分高級(jí)技巧:
.pyc
files are ignored and .py
files are compiled to optimized bytecode.
以 -O 參數(shù)調(diào)用Python解釋器時(shí),會(huì)生成優(yōu)化代碼并保存在 .pyo 文件中,F(xiàn)在的優(yōu)化器沒(méi)有太多幫助;它只是刪除了斷言(assert )語(yǔ)句。使用 -O 參參數(shù),所有的代碼都會(huì)被優(yōu)化;.pyc
文件被忽略, .py
文件被編譯為優(yōu)化代碼。
__doc__
strings are removed from the
bytecode, resulting in more compact .pyo files. Since some
programs may rely on having these available, you should only use this
option if you know what you're doing.
向Python解釋器傳遞兩個(gè) -O 參數(shù)(-OO)會(huì)執(zhí)行完全優(yōu)化的二進(jìn)制優(yōu)化編譯,這偶爾會(huì)生成錯(cuò)誤的程序,F(xiàn)在的優(yōu)化器,只是從二進(jìn)制代碼中刪除了 __doc__
符串,生成更為緊湊的 .pyo 文件。因?yàn)槟承┏绦蛞蕾囉谶@些變量的可用性,你應(yīng)該只在確定無(wú)誤的場(chǎng)合使用這一選項(xiàng)。
來(lái)自 .pyc 文件或 .pyo 文件中的程序不會(huì)比來(lái)自 .py 文件的運(yùn)行更快; .pyc 或 .pyo 文件只是在它們加載的時(shí)候更快一些。
通過(guò)腳本名在命令行運(yùn)行腳本時(shí),不會(huì)將為該腳本創(chuàng)建的二進(jìn)制代碼寫(xiě)入 .pyc 或.pyo 文件。當(dāng)然,把腳本的主要代碼移進(jìn)一個(gè)模塊里,然后用一個(gè)小的解構(gòu)腳本導(dǎo)入這個(gè)模塊,就可以提高腳本的啟動(dòng)速度。也可以直接在命令行中指定一個(gè) .pyc 或 .pyo 文件。
對(duì)于同一個(gè)模塊(這里指例程 spam.py --譯者),可以只有 spam.pyc 文件(或者 spam.pyc ,在使用 -O 參數(shù)時(shí))而沒(méi)有 spam.py 文件。這樣可以打包發(fā)布比較難于逆向工程的Python代碼庫(kù)。
compileall 模塊 可以為指定目錄中的所有模塊創(chuàng)建 .pyc 文件(或者使用 .pyo 參數(shù)創(chuàng)建.pyo文件)。
Python comes with a library of standard modules, described in a separate
document, the Python Library Reference
(``Library Reference'' hereafter). Some modules are built into the
interpreter; these provide access to operations that are not part of
the core of the language but are nevertheless built in, either for
efficiency or to provide access to operating system primitives such as
system calls. The set of such modules is a configuration option which
also depends on the underlying platform For example,
the amoeba module is only provided on systems that somehow
support Amoeba primitives. One particular module deserves some
attention: sys, which is built into every
Python interpreter. The variables sys.ps1
and
sys.ps2
define the strings used as primary and secondary
prompts:
Python帶有一個(gè)標(biāo)準(zhǔn)模塊庫(kù),并發(fā)布有獨(dú)立的文檔,名為 Python 庫(kù)參考手冊(cè) (此后稱其為“庫(kù)參考手冊(cè)”)。有一些模塊內(nèi)置于解釋器之中,這些操作的訪問(wèn)接口不是語(yǔ)言內(nèi)核的一部分,但是已經(jīng)內(nèi)置于解釋器了。這既是為了提高效率,也是為了給系統(tǒng)調(diào)用等操作系統(tǒng)原生訪問(wèn)提供接口。這類模塊集合是一個(gè)依賴于底層平臺(tái)的配置選項(xiàng)。例如,amoeba 模塊只提供對(duì) Amoeba
原生系統(tǒng)的支持。有一個(gè)具體的模塊值得注意:sys ,這個(gè)模塊內(nèi)置于所有的Python解釋器。變量 sys.ps1
和 sys.ps2
定義了主提示符和副助提示符字符串:
>>> import sys >>> sys.ps1 '>>> ' >>> sys.ps2 '... ' >>> sys.ps1 = 'C> ' C> print 'Yuck!' Yuck! C>
These two variables are only defined if the interpreter is in interactive mode.
這兩個(gè)變量只在解釋器的交互模式下有意義。
The variable sys.path
is a list of strings that determine the
interpreter's search path for modules. It is initialized to a default
path taken from the environment variable PYTHONPATH, or from
a built-in default if PYTHONPATH is not set. You can modify
it using standard list operations:
變量 sys.path
是解釋器模塊搜索路徑的字符串列表。它由環(huán)境變量 PYTHONPATH 初始化,如果沒(méi)有設(shè)定 PYTHONPATH ,就由內(nèi)置的默認(rèn)值初始化。你可以用標(biāo)準(zhǔn)的字符串操作修改它:
>>> import sys >>> sys.path.append('/ufs/guido/lib/python')
The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:
內(nèi)置函數(shù) dir() 用于按模塊名搜索模塊定義,它返回一個(gè)字符串類型的存儲(chǔ)列表:
>>> import fibo, sys >>> dir(fibo) ['__name__', 'fib', 'fib2'] >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions']
Without arguments, dir() lists the names you have defined currently:
無(wú)參數(shù)調(diào)用時(shí), dir() 函數(shù)返回當(dāng)前定義的命名:
>>> a = [1, 2, 3, 4, 5] >>> import fibo, sys >>> fib = fibo.fib >>> dir() ['__name__', 'a', 'fib', 'fibo', 'sys']
Note that it lists all types of names: variables, modules, functions, etc.
該列表列出了所有類型的名稱:變量,模塊,函數(shù),等等:
dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module __builtin__:
dir() 不會(huì)列出內(nèi)置函數(shù)和變量名。如果你想列出這些內(nèi)容,它們?cè)跇?biāo)準(zhǔn)模塊 __builtin__中定義:
>>> import __builtin__ >>> dir(__builtin__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod', 'str', 'string', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
Packages are a way of structuring Python's module namespace by using ``dotted module names''. For example, the module name A.B designates a submodule named "B" in a package named "A". Just like the use of modules saves the authors of different modules from having to worry about each other's global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other's module names.
包通常是使用用“圓點(diǎn)模塊名”的結(jié)構(gòu)化模塊命名空間。例如,名為 A.B 的模塊表示了名為 "B" 的包中名為 "A" 的子模塊。正如同用模塊來(lái)保存不同的模塊架構(gòu)可以避免全局變量之間的相互沖突,使用圓點(diǎn)模塊名保存像 NumPy 或 Python Imaging Library 之類的不同類庫(kù)架構(gòu)可以避免模塊之間的命名沖突。
Suppose you want to design a collection of modules (a ``package'') for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav, .aiff, .au), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. There are also many different operations you might want to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform these operations. Here's a possible structure for your package (expressed in terms of a hierarchical filesystem):
假設(shè)你現(xiàn)在想要設(shè)計(jì)一個(gè)模塊集(一個(gè)“包”)來(lái)統(tǒng)一處理聲音文件和聲音數(shù)據(jù)。存在幾種不同的聲音格式(通常由它們的擴(kuò)展名來(lái)標(biāo)識(shí),例如:.wav , .aiff , .au) ),于是,為了在不同類型的文件格式之間轉(zhuǎn)換,你需要維護(hù)一個(gè)不斷增長(zhǎng)的包集合?赡苣氵想要對(duì)聲音數(shù)據(jù)做很多不同的操作(例如混音,添加回聲,應(yīng)用平衡功能,創(chuàng)建一個(gè)人造效果),所以你要加入一個(gè)無(wú)限流模塊來(lái)執(zhí)行這些操作。你的包可能會(huì)是這個(gè)樣子(通過(guò)分級(jí)的文件體系來(lái)進(jìn)行分組):
Sound/ Top-level package __init__.py Initialize the sound package Formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... Effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... Filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ...
When importing the package, Python searches through the directories
on sys.path
looking for the package subdirectory.
導(dǎo)入模塊時(shí),Python通過(guò) sys.path
中的目錄列表來(lái)搜索存放包的子目錄。
The __init__.py files are required to make Python treat the
directories as containing packages; this is done to prevent
directories with a common name, such as "string", from
unintentionally hiding valid modules that occur later on the module
search path. In the simplest case, __init__.py can just be an
empty file, but it can also execute initialization code for the
package or set the __all__
variable, described later.
必須要有一個(gè) __init__.py 文件的存在,才能使Python視該目錄為一個(gè)包;這是為了防止某些目錄使用了"string" 這樣的通用名而無(wú)意中在隨后的模塊搜索路徑中覆蓋了正確的模塊。最簡(jiǎn)單的情況下,__init__.py 可以只是一個(gè)空文件,不過(guò)它也可能包含了包的初始化代碼,或者設(shè)置了 __all__
變量,后面會(huì)有相關(guān)介紹。
Users of the package can import individual modules from the package, for example:
包用戶可以從包中導(dǎo)入合法的模塊,例如:
import Sound.Effects.echo
This loads the submodule Sound.Effects.echo. It must be referenced with its full name.
這樣就導(dǎo)入了 Sound.Effects.echo 子模塊。它必需通過(guò)完整的名稱來(lái)引用。
Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
An alternative way of importing the submodule is:
導(dǎo)入包時(shí)有一個(gè)可以選擇的方式:
from Sound.Effects import echo
This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:
這樣就加載了 echo 子模塊,并且使得它在沒(méi)有包前綴的情況下也可以使用,所以它可以如下方式調(diào)用:
echo.echofilter(input, output, delay=0.7, atten=4)
Yet another variation is to import the desired function or variable directly:
還有另一種變體用于直接導(dǎo)入函數(shù)或變量:
from Sound.Effects.echo import echofilter
Again, this loads the submodule echo, but this makes its function echofilter() directly available:
這樣就又一次加載了 echo 子模塊,但這樣就可以直接調(diào)用它的 echofilter() 函數(shù):
echofilter(input, output, delay=0.7, atten=4)
Note that when using from package import item
, the
item can be either a submodule (or subpackage) of the package, or some
other name defined in the package, like a function, class or
variable. The import
statement first tests whether the item is
defined in the package; if not, it assumes it is a module and attempts
to load it. If it fails to find it, an
ImportError exception is raised.
需要注意的是使用 from package import item
方式導(dǎo)入包時(shí),這個(gè)子項(xiàng)(item)既可以是包中的一個(gè)子模塊(或一個(gè)子包),也可以是包中定義的其它命名,像函數(shù)、類或變量。import
語(yǔ)句首先核對(duì)是否包中有這個(gè)子項(xiàng),如果沒(méi)有,它假定這是一個(gè)模塊,并嘗試加載它。如果沒(méi)有找到它,會(huì)引發(fā)一個(gè) ImportError 異常。
Contrarily, when using syntax like import
item.subitem.subsubitem
, each item except for the last must be
a package; the last item can be a module or a package but can't be a
class or function or variable defined in the previous item.
相反,使用類似import item.subitem.subsubitem
這樣的語(yǔ)法時(shí),這些子項(xiàng)必須是包,最后的子項(xiàng)可以是包或模塊,但不能是前面子項(xiàng)中定義的類、函數(shù)或變量。
Now what happens when the user writes from Sound.Effects import
*
? Ideally, one would hope that this somehow goes out to the
filesystem, finds which submodules are present in the package, and
imports them all. Unfortunately, this operation does not work very
well on Mac and Windows platforms, where the filesystem does not
always have accurate information about the case of a filename! On
these platforms, there is no guaranteed way to know whether a file
ECHO.PY should be imported as a module echo,
Echo or ECHO. (For example, Windows 95 has the
annoying practice of showing all file names with a capitalized first
letter.) The DOS 8+3 filename restriction adds another interesting
problem for long module names.
那么當(dāng)用戶寫(xiě)下 from Sound.Effects import *
時(shí)會(huì)發(fā)生什么事?理想中,總是希望在文件系統(tǒng)中找出包中所有的子模塊,然后導(dǎo)入它們。不幸的是,這個(gè)操作在 Mac 和 Windows 平臺(tái)上工作的并不太好,這些文件系統(tǒng)的文件大小寫(xiě)并不敏感!在這些平臺(tái)上沒(méi)有什么方法可以確保一個(gè)叫ECHO.PY 的文件應(yīng)該導(dǎo)入為模塊 echo 、 Echo 或 ECHO 。(例如,Windows 95有一個(gè)討厭的習(xí)慣,它會(huì)把所有的文件名都顯示為首字母大寫(xiě)的風(fēng)格。)DOS 8+3文件名限制又給長(zhǎng)文件名模塊帶來(lái)了另一個(gè)有趣的問(wèn)題。
The only solution is for the package author to provide an explicit
index of the package. The import statement uses the following
convention: if a package's __init__.py code defines a list
named __all__
, it is taken to be the list of module names that
should be imported when from package import *
is
encountered. It is up to the package author to keep this list
up-to-date when a new version of the package is released. Package
authors may also decide not to support it, if they don't see a use for
importing * from their package. For example, the file
Sounds/Effects/__init__.py could contain the following code:
對(duì)于包的作者來(lái)說(shuō)唯一的解決方案就是給提供一個(gè)明確的包索引。import 語(yǔ)句按如下條件進(jìn)行轉(zhuǎn)換:執(zhí)行 from package import *
時(shí),如果包中的 __init__.py 代碼定義了一個(gè)名為 __all__
的鏈表,就會(huì)按照鏈表中給出的模塊名進(jìn)行導(dǎo)入。新版本的包發(fā)布時(shí)作者可以任意更新這個(gè)鏈表。如果包作者不想 import * 的時(shí)候?qū)胨麄兊陌兴心K,那么也可能會(huì)決定不支持它(import *)。例如, Sounds/Effects/__init__.py 這個(gè)文件可能包括如下代碼:
__all__ = ["echo", "surround", "reverse"]
This would mean that from Sound.Effects import *
would
import the three named submodules of the Sound package.
這意味著 from Sound.Effects import *
語(yǔ)句會(huì)從 Sound 包中導(dǎo)入以上三個(gè)已命名的子模塊。
If __all__
is not defined, the statement from Sound.Effects
import *
does not import all submodules from the package
Sound.Effects into the current namespace; it only ensures that the
package Sound.Effects has been imported (possibly running its
initialization code, __init__.py) and then imports whatever names are
defined in the package. This includes any names defined (and
submodules explicitly loaded) by __init__.py. It also includes any
submodules of the package that were explicitly loaded by previous
import statements. Consider this code:
如果沒(méi)有定義 __all__
, from Sound.Effects import *
語(yǔ)句不會(huì)從 Sound.Effects 包中導(dǎo)入所有的子模塊。Effects 導(dǎo)入到當(dāng)前的命名空間,只能確定的是導(dǎo)入了 Sound.Effects 包(可能會(huì)運(yùn)行 __init__.py 中的初始化代碼)以及包中定義的所有命名會(huì)隨之導(dǎo)入。這樣就從 __init__.py 中導(dǎo)入了每一個(gè)命名(以及明確導(dǎo)入的子模塊)。同樣也包括了前述的import語(yǔ)句從包中明確導(dǎo)入的子模塊,考慮以下代碼:
import Sound.Effects.echo import Sound.Effects.surround from Sound.Effects import *
In this example, the echo and surround modules are imported in the
current namespace because they are defined in the
Sound.Effects package when the from...import
statement
is executed. (This also works when __all__
is defined.)
在這個(gè)例子中,echo和surround模塊導(dǎo)入了當(dāng)前的命名空間,這是因?yàn)閳?zhí)行 from...import
語(yǔ)句時(shí)它們已經(jīng)定義在 Sound.Effects 包中了(定義了 __all__
時(shí)也會(huì)同樣工作)。
Note that in general the practice of importing *
from a module or
package is frowned upon, since it often causes poorly readable code.
However, it is okay to use it to save typing in interactive sessions,
and certain modules are designed to export only names that follow
certain patterns.
需要注意的是習(xí)慣上不主張從一個(gè)包或模塊中用 import *
導(dǎo)入所有模塊,因?yàn)檫@樣的通常意味著可讀性會(huì)很差。然而,在交互會(huì)話中這樣做可以減少輸入,相對(duì)來(lái)說(shuō)確定的模塊被設(shè)計(jì)成只導(dǎo)出確定的模式中命名的那一部分。
Remember, there is nothing wrong with using from Package
import specific_submodule
! In fact, this is the
recommended notation unless the importing module needs to use
submodules with the same name from different packages.
記住, from Package import specific_submodule
沒(méi)有錯(cuò)誤!事實(shí)上,除非導(dǎo)入的模塊需要使用其它包中的同名子模塊,否則這是受到推薦的寫(xiě)法。
The submodules often need to refer to each other. For example, the
surround module might use the echo module. In fact,
such references
are so common that the import statement first looks in the
containing package before looking in the standard module search path.
Thus, the surround module can simply use import echo
or
from echo import echofilter
. If the imported module is not
found in the current package (the package of which the current module
is a submodule), the import statement looks for a top-level
module with the given name.
子模塊之間經(jīng)常需要互相引用。例如,surround 模塊可能會(huì)引用 echo 模塊。事實(shí)上,這樣的引用如此普遍,以致于 import 語(yǔ)句會(huì)先搜索包內(nèi)部,然后才是標(biāo)準(zhǔn)模塊搜索路徑。因此 surround 模塊可以簡(jiǎn)單的調(diào)用 import echo
或者 from echo import echofilter
。如果沒(méi)有在當(dāng)前的包中發(fā)現(xiàn)要導(dǎo)入的模塊,import 語(yǔ)句會(huì)依據(jù)指定名尋找一個(gè)頂級(jí)模塊。
When packages are structured into subpackages (as with the
Sound package in the example), there's no shortcut to refer
to submodules of sibling packages - the full name of the subpackage
must be used. For example, if the module
Sound.Filters.vocoder needs to use the echo module
in the Sound.Effects package, it can use from
Sound.Effects import echo
.
如果包中使用了子包結(jié)構(gòu)(就像示例中的 Sound 包),不存在什么從鄰近的包中引用子模塊的便捷方法--必須使用子包的全名。例如,如果 Sound.Filters.vocoder 包需要使用 Sound.Effects 包中的 echosa 模塊,它可以使用 from Sound.Effects import echo
。
Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package's __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.
包支持一個(gè)更為特殊的變量, __path__ 。 在包的 __init__.py 文件代碼執(zhí)行之前,該變量初始化一個(gè)目錄名列表。該變量可以修改,它作用于包中的子包和模塊的搜索功能。
While this feature is not often needed, it can be used to extend the set of modules found in a package.
這個(gè)功能可以用于擴(kuò)展包中的模塊集,不過(guò)它不常用。